I have a VueJS 2 component that looks something like this:
<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>
I want to write a Jest test that checks that when onFavorite is run trackFavorite is called. Tried something like this:
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('calls trackFavorite', () => {
expect(wrapper.vm.trackFavorite).toHaveBeenCalled()
})
})
})
But it doesn't work as trackFavorite is not replaced by the Jest mock function.
jest.mock() at the top of the test file to mock the entire import (including its methods).require() the file within the test to access the mock.trackFavorite method is called.// FavoriteButton.spec.js
import { shallowMount } from '@vue/test-utils'
import FavoriteButton from '@/components/FavoriteButton.vue'
jest.mock('@/utils/analytics') 1️⃣
describe('FavoriteButton.vue', () => {
it('calls trackFavorite on button click', async () => {
const analytics = require('@/utils/analytics') 2️⃣
const wrapper = shallowMount(FavoriteButton)
await wrapper.find('button').trigger('click')
expect(analytics.trackFavorite).toHaveBeenCalled() 3️⃣
})
})