How to Unit Test a Method in a Vue.js Component using jest
Calling component method
The wrapper provides access to the component instance via its vm
property, so you could call the method directly with:
wrapper.vm.doSomeWork()
Setting props
- The mounting options (passed to
shallowMount()
ormount()
) include thepropsData
property that could be used to initialize the component'sprops
before mounting. - You could also use the wrapper's
setProps()
after the component has already been mounted.
Example:
it('...', () => {
const wrapper = shallowMount(MyComponent, {
propsData: {
myItems: [
{ id: 200, bar: false },
{ id: 300, bar: false }
]
}
});
// OR
wrapper.setProps({
myItems: [
{ id: 400: bar: true }
]
})
})
Modifying component data property
- The mounting options includes the
data
property that could be used to initialize the component's data before mounting. - You could also use the wrapper's
setData()
after the component has already mounted. - You could access the component's data property directly through the wrapper's
vm
property.
Example:
it('...', () => {
const wrapper = shallowMount(MyComponent, {
data() {
return {
foo: 1
}
}
});
// OR
wrapper.setData({ foo: 2 })
// OR
wrapper.vm.foo = 3
})
Full example
Altogether, your test might look similar to this:
import { createLocalVue, shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent'
describe('MyComponent', () => {
it('When foo is set to -something-, set bar to true', () => {
const myItems = [
{ id: 200, bar: false },
{ id: 300, bar: false }
]
const localVue = createLocalVue()
const wrapper = shallowMount(MyComponent, {
localVue,
propsData: {
myItems
}
})
wrapper.vm.foo = 'something'
wrapper.vm.doSomeWork()
expect(myItems[0].bar).toBe(true)
})
})
demo