我在试着理解用Vitest嘲弄Vue-Router的逻辑。
为此,我尝试在一个非常简单的项目上设置和模拟我的测试环境。当我试图按照Vue的正式文档-测试-Utils进行操作时,总是会出现错误。我不知道是不是因为他们用的是小丑。
使用真vue路由器解决了我的问题,但我认为最好是模拟vue路由器。
下面,我首先传递项目的源代码,然后是我收到的错误。
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>
<div>Home</div>
</template>
Home.spec.ts
import {expect, it, vi} from "vitest";
import {mount} from "@vue/test-utils";
import Home from "../src/components/Home.vue"
it('Home Test', async () => {
const wrapper = mount(Home)
expect(wrapper.exists()).toBeTruthy()
})
vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
include: ['./test/**/*.spec.ts'],
exclude: ['node_modules', 'dist'],
globals: true
}
})
我的错误消息如下:
我试过的方法
我试图像下面这样模拟vue-路由器。
vi.mock('vue-router', () => ({
useRoute: vi.fn(),
}))
或者只是
vi.mock('vue-router')
这是我最后一个Home.spec.ts文件
import {expect, it, vi} from "vitest";
import {mount} from "@vue/test-utils";
import Home from "../src/components/Home.vue"
vi.mock('vue-router')
it('Home Test', async () => {
const wrapper = mount(Home, {
global: {
stubs: ["router-link", "router-view"]
}
})
expect(wrapper.exists()).toBeTruthy()
})
发布于 2022-10-27 06:35:22
首先,我希望在router-link
或router-view
中看到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>
所以,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()
函数中的存根应该与模板中使用的组件相关(因此,如果不使用<router-view>
,则不应将其作为存根列出)希望这有帮助,干杯!
https://stackoverflow.com/questions/74209044
复制相似问题