I'm writing a jest unit test for my Vuejs 2 (Vuetify) component. Setup is pretty simple.
Inside the component I have a prop, which is an object with nested fields:
props: ['testObject']
And I have a computed property that returns a field from that prop:
computed: {
myField() {
return this.testObject.testField;
}
}
And I write a Jest test:
wrapper = mount(MyComponent, {
mocks: {
propsData: {
testObject: { testField: 'My Test Value' }
}
},
});
it("should return a test field", () => {
const field = wrapper.vm.$options.computed.myField();
expect(field).toBe('My Test Value');
});
When I run the test I get the following:
TypeError: Cannot read property 'testField' of undefined
So it calls computed propperty, but testObject is undefined.
Any idea what's going on?
@vue/test-utils: 1.3.0 @vue/vue2-jest: 28.0.1 @types/jest: 28.1.3 jest: 28.1.1
CodePudding user response:
Try to mount your component this way:
wrapper = mount(MyComponent, {
propsData: {
testObject: { testField: 'My Test Value' }
}
});
Check this documentation for more informations.
CodePudding user response:
Alright, I worked it out by doing this:
it("should return a test field", async () => {
wrapper.vm.$options.computed.testObject.call({ testField: 'My Test Value' });
...
});
Hope that will help for those who experience the same issue.
CodePudding user response:
Your code failing because the this
inside the computed function referencing $options
. You need to access computed as a vm
's attribute, not the $option
. Just do this.
expect(wrapper.vm.myField).toBe('My Test Value');
But there is one more problem here. Actually you don't need to test the computed
value. Because if you accidentally remove this computed value rendering from template, this tests will still be passed. Instead, test what this string is rendered in html.
expect(wrapper.text()).toContain('My Test Value');