9

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


});
tony19
  • 125,647
  • 18
  • 229
  • 307
DevLime
  • 937
  • 2
  • 9
  • 19

2 Answers2

13

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)

})
tony19
  • 125,647
  • 18
  • 229
  • 307
DevLime
  • 937
  • 2
  • 9
  • 19
2

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.

  • 1
    why do you prefer wrapper.vm.$data ?? – Kick Buttowski Apr 09 '21 at 02:52
  • 1
    @KickButtowski I am a bit new to Vue. So, for syntactical clarity, I use an extra "$data" so that I don't get confused when I read the code in the future. :) I am not aware about the performance comparison among the 2 methods though. – chess_madridista May 08 '21 at 14:37
  • 2
    For anyone else stumbling over this: `wrapper.vm.$data.count` seems to return `undefined` with Vue 3 and vue-test-utils 2. However, `wrapper.vm.count` seems to work fine. – Patrick Feb 09 '22 at 08:11