Search code examples
vue.jsvuejs2chaivue-test-utils

Is accessing `data` properties via `wrapper.vm` the correct way, as per the docs?


How can I access a data property in a Vue test instance?

I see that you can access props, but there's no data equivalent. I can grab a data property by using something like wrapper.vm.foo, but I feel that there is another way of doing this that may fall more in the lines of the test framework.

App.vue

<script>
    export default {
      data() {
        return {
          foo: 'bar'
        }
      }
    }
</script>

App.spec.js

import { shallowMount } from '@vue/test-utils'
import App from '@/App.vue'
import { expect } from 'chai';

describe("App.vue", () => {

  let wrapper;

  beforeEach(() => {
    // use this to check the state of anything in the view
    wrapper = shallowMount(App)
  });

  it("Module has the expected data attribute", () => {
    expect(wrapper.vm.foo).to.equal('bar'); // passes

    expect(wrapper.foo).to.equal('bar'); // fails
    expect(wrapper.data('foo')).to.equal('bar'); // fails
    expect(wrapper.data().foo).to.equal('bar'); // fails
  });


  it('simple passing test', () => {
    expect(1).to.equal(1);
  });


});

Solution

  • It may be possible, but .vm is the correct way.

    Example from the vue-test-utils documentation:

    it('button click should increment the count', () => {
    
      expect(wrapper.vm.count).toBe(0)
      const button = wrapper.find('button')
      button.trigger('click')
    
      // `wrapper.vm.count` it is!
      expect(wrapper.vm.count).toBe(1)
    
    })