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);
});
});
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)
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With