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 enjoying this approach, but I have run into a roadblock in regards to adding methods to a Vue instance, and testing that they have been called when the event fires from the element in the template.
I cannot find any suggestions as to how I can mock a Vue method given that if I mock the proxied method, it ends up not being called (I'm using Jest and Vue Test Utils).
I am also using Cypress, so I can fill in this test in e2e, but I would like to be able to cover as much as possible with unit tests.
I own the book "Testing Vue.js Applications" by Edd Yerburgh, but in the section regarding testing component methods, he simply states the following:
Often, components use methods internally. For example, to log to the console when a button is clicked [...] You can think of these as private methods—they aren’t intended to be used outside of the component. Private methods are implementation details, so you don’t write tests for them directly.
This approach obviously does not allow the stricter laws of TDD to be followed, so how do the TDD purists handle this?
ButtonComponent.vue
<template>
<button @click="method">Click me</button>
</template>
<script>
export default: {
methods: {
method () {
// Have I been called?
}
}
}
</script>
ButtonComponent.spec.js
it('will call the method when clicked', () => {
const wrapper = shallowMount(ButtonComponent)
const mockMethod = jest.fn()
wrapper.vm.method = mockMethod
const button = wrapper.find('button')
button.vm.$emit('click')
expect(mockMethod).toHaveBeenCalled()
// Expected mock function to have been called, but it was not called
})
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…