首先,我希望在 Home.vue
中看到 router-link
或 router-view
:
<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>
因此,Home.spec.ts
應(yīng)該是這樣的:
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(); }); });
一些評論/建議:
.spyOn()
和 .mockImplementation...()
進(jìn)行監(jiān)視和模擬.toHaveBeenCalled...()
檢查模擬是否按預(yù)期工作mount()
函數(shù)中的存根應(yīng)與模板中使用的組件相關(guān)(因此,如果您不使用
,它不應(yīng)該被列為存根)希望有幫助, 干杯!