P粉2949544472023-08-26 00:01:26
First, I want to see router-link
or router-view
in Home.vue
:
<script setup lang="ts"> import { onMounted } from 'vue'; import { useRoute } from 'vue-router'; const route = useRoute(); onMounted(() => { console.log(route.query); }); </script> <template> <router-link to="home">Go to home</router-link> <router-view /> </template>
So, Home.spec.ts
should look like this:
import { expect, it, vi } from 'vitest'; import { mount } from '@vue/test-utils'; import * as VueRouter from 'vue-router'; import Home from '../src/components/Home.vue'; describe('./path/to/Home.vue', () => { const useRouteSpy = vi.spyOn(VueRouter, 'useRoute'); const getWrapper = () => mount(Home as any, { global: { stubs: { 'router-link': { template: '<div/>' }, 'router-view': { template: '<div/>' }, }, }, }); it('the component should be mounted', () => { // ARRANGE const useRouteMock = useRouteSpy.mockImplementationOnce({ query: 'query' }); // ACT const wrapper = getWrapper(); // ASSERT expect(useRouteMock).toHaveBeenCalled(); expect(wrapper.exists()).toBeTruthy(); }); });
Some comments/suggestions:
.spyOn()
and .mockImplementation...()
for monitoring and simulation.toHaveBeenCalled...()
Check if the mock is working as expectedmount()
The stub in the function should be related to the component used in the template (so if you don't use
it shouldn't be listed as a stub)Hope it helps, cheers!