我试图理解用Vitest嘲笑Vue-Router的逻辑。
为此,我尝试在一个非常简单的项目上设置并模拟我的测试环境。当我试图根据Vue-Test-Utils的官方文档进行操作时,我总是得到一个错误。我不知道这是否是因为他们使用Jest。
使用真实的vue-router解决了我的问题,但我认为最好是模仿vue-router。
下面,我首先传达了项目的源代码,然后是我收到的错误。
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
}
})
型
我的错误信息如下:..
x1c 0d1x的数据
的
尝试过的方法
我试着模仿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()
})
型
2条答案
按热度按时间pqwbnv8z1#
首先,我希望在
Home.vue
中看到router-link
或router-view
:字符串
Home.spec.ts
应该是这样的:型
一些评论/建议:
.spyOn()
和.mockImplementation...()
进行监视和模拟.toHaveBeenCalled...()
检查mock是否按预期工作mount()
函数中的存根应该与模板中使用的组件相关(因此,如果您没有使用<router-view>
,则不应将其列为存根)希望有帮助,干杯!
o2rvlv0m2#
如果有人需要做同样的事情,现在你可以很容易地模拟vue路由器使用vue-router-mock
字符串