Vue3 + @vue/test-utils@next + VueRouter4 + Jest 单元测报错?
单元测试内容
test("Foo.vue GoAbout", () => {
const vm = shallowMount(Foo as any, {});
const oBtn1 = vm.find("#btn1");
oBtn1?.trigger("click");
expect(vm.vm.$route.path).toBe('/about')
});
组件
<template>
<div>
<div id="box">{{ value }}</div>
<button id="btn" @click="onStoreChange">Change Store</button>
<button id="btn1" @click="onGoToAbout">Go To About</button>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useFooStore } from "../store/module/Foo";
import { useRouter } from "vue-router";
const fooStore = useFooStore();
const router = useRouter();
interface props {
value?: string;
};
defineProps<props>();
const abc = ref("123123");
const onStoreChange = () => {
fooStore.setFooValue("Aaron");
};
const onGoToAbout = () => {
router.push({
name: "About"
})
};
</script>
报错内容如下:
TypeError: Cannot read property 'push' of undefined
29 |
30 | const onGoToAbout = () => {
> 31 | router.push({
| ^
32 | name: "About"
33 | })
34 | };
回复
1个回答
test
2024-07-06
你再试试在测试文件的顶部添加以下 mock:
jest.mock("vue-router", () => {
const realModule = jest.requireActual("vue-router");
const mockRouter = {
...realModule,
useRouter: () => ({
push: (route: any) => {
mockRouter.currentRoute.value = route;
},
currentRoute: {
value: null,
},
}),
};
return mockRouter;
});
接下来,修改测试用例以使用新的 mock 方法:
import { shallowMount } from "@vue/test-utils";
import Foo from "@/components/Foo.vue";
import { useRouter } from "vue-router";
test("Foo.vue GoAbout", async () => {
const wrapper = shallowMount(Foo);
const oBtn1 = wrapper.find("#btn1");
await oBtn1.trigger("click");
const router = useRouter();
expect(router.currentRoute.value.name).toBe("About");
});
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容