I am doing some unit testing for components. However, in some components, I have something running on the mounted
hook that is making my test fail.
I have managed to mock the methods that I do not need. However, I was wondering if there is a workaround mocking the mounted
hook itself.
@/components/attendeesList.vue
<template>
<div>
<span> This is a test </span>
</div>
</template>
JS
<script>
methods: {
testMethod: function() {
// Whatever is in here I have managed to mock it
}
},
mounted: {
this.testMethod();
}
</script>
Test.spec.js
import { mount, shallowMount } from '@vue/test-utils'
import test from '@/components/attendeesList.vue'
describe('mocks a method', () => {
test('is a Vue instance', () => {
const wrapper = shallowMount(attendeesList, {
testMethod:jest.fn(),
})
expect(wrapper.isVueInstance()).toBeTruthy()
})
Currently, vue-test-utils
does not support mocking lifecycle hooks, but you can mock the method called from the mounted
hook. In your case, to mock testMethod()
, use jest.spyOn
:
const testMethod = jest.spyOn(HelloWorld.methods, 'testMethod')
const wrapper = shallowMount(HelloWorld)
expect(testMethod).toHaveBeenCalledWith("hello")
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