I\'m learning TDD whilst building my Vue app, and trying to abide by the strict laws of only writing enough production code to satisfy a failing unit test. I am really enjoy
jest.spyOn(Component.methods, 'METHOD_NAME')
You could use jest.spyOn to mock the component method before mounting:
import MyComponent from '@/components/MyComponent.vue'
describe('MyComponent', () => {
it('click does something', async () => {
const mockMethod = jest.spyOn(MyComponent.methods, 'doSomething')
await shallowMount(MyComponent).find('button').trigger('click')
expect(mockMethod).toHaveBeenCalled()
})
})
The official recommendation is to "abstract the hard parts away", and use Jest's various mocking mechanisms to mock the abstracted module invoked by the component under test.
For example, to verify a click
-handler is invoked:
click
-handler's body into a shared JavaScript file.jest.mock()
to mock the exported functions of the shared module.// @/components/MyComponent/utils.js
export function doSomething() { /*...*/ } //1️⃣
// @/components/MyComponent/MyComponent.vue (<script>)
import { doSomething } from '@/components/MyComponent/utils' //2️⃣
export default {
methods: {
onClick() {
doSomething() //1️⃣
}
}
}
// @/test/MyComponent.spec.js
import { doSomething } from '@/components/MyComponent/utils' //2️⃣
jest.mock('@/components/MyComponent/utils') //3️⃣
describe('MyComponent', () => {
beforeEach(() => doSomething.mockClear()) //4️⃣
it('click does something', async () => {
await shallowMount(MyComponent).find('button').trigger('click')
expect(doSomething).toHaveBeenCalled()
})
})
setMethods()
(pre v1.0)Use setMethods()
(deprecated as of v1.0) to overwrite a component method:
describe('MyComponent', () => {
it('click does something', async () => {
// Option A:
const mockMethod = jest.fn()
const wrapper = shallowMount(MyComponent)
wrapper.setMethods({ doSomething: mockMethod })
await wrapper.find('button').trigger('click')
expect(mockMethod).toHaveBeenCalled()
// Option B:
const mockMethod = jest.fn()
const wrapper = shallowMount(MyComponent, {
methods: {
doSomething: mockMethod
}
})
await wrapper.find('button').trigger('click')
expect(mockMethod).toHaveBeenCalled()
})
})
demo