Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  });


});
like image 315
DevLime Avatar asked Feb 28 '19 10:02

DevLime


2 Answers

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)

})
like image 108
DevLime Avatar answered Nov 15 '22 08:11

DevLime


Modifying DevLime's answer a bit, I prefer to use wrapper.vm.$data instead of wrapper.vm as follows:

it('button click should increment the count', () => {

    expect(wrapper.vm.$data.count).toBe(0)
    const button = wrapper.find('button')
    button.trigger('click')

    // `wrapper.vm.$data.count` it is!
    expect(wrapper.vm.$data.count).toBe(1)

})

It works fine with V2 of Vue test utils.

like image 27
chess_madridista Avatar answered Nov 15 '22 08:11

chess_madridista