I've created a VueJS 2 component that has the following structure:
<template>
<div>
<button @click="onFavorite">
Add to favorites
</button>
</div>
</template>
<script>
import { trackFavorite } from "@/utils/analytics";
export default {
name: "FavoriteButton",
methods: {
onFavorite() {
trackFavorite("click", "favorite");
[ ... ]
}
}
}
</script>
Now, I am attempting to write a Jest test to verify that when onFavorite
is executed, trackFavorite
is called. Here's a snippet of what I've tried:
import { shallowMount } from '@vue/test-utils';
import FavoriteButton from '../FavoriteButton'
describe("FavoriteButton", () => {
let wrapper
beforeEach(() => {
wrapper = shallowMount(FavoriteButton)
})
describe('.onFavorite', () => {
beforeEach(() => {
wrapper.vm.trackFavorite = jest.fn()
wrapper.vm.onFavorite()
})
it('should invoke trackFavorite', () => {
expect(wrapper.vm.trackFavorite).toHaveBeenCalled()
})
})
})
However, this approach is not working as expected because trackFavorite
is not being replaced by the Jest mock function.