P粉2949544472023-08-26 00:01:26
首先,我希望在 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
应该是这样的:
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...()
进行监视和模拟.toHaveBeenCalled...()
检查模拟是否按预期工作mount()
函数中的存根应与模板中使用的组件相关(因此,如果您不使用
,它不应该被列为存根)希望有帮助, 干杯!