I'm using Vue 3 and Vue-Router for my app, and I'm having trouble when creating unit tests with Jest on components that use useRoute(), such as the following:
<template>
<div :class="{ 'grey-background': !isHomeView }" />
</template>
<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useRoute } from 'vue-router';
export default defineComponent({
setup: () => {
const isHomeView = computed(() => {
return useRoute().name === 'Home';
});
return {
isHomeView,
};
},
});
</script>
The computed property is using useRoute(), and it is used in the template.
When I make a Jest test on this component, an error is thrown saying TypeError: Cannot read property 'name' of undefined.
I tried mocking useRoute like so :
jest.mock('vue-router', () => ({ useRoute: jest.fn() })); and then on the beforeEach: useRoute.mockReturnValueOnce({ name: 'Home' });, but it doesn't work.
I'm not talking about Vue 2 in which the router works differently but Vue 3.