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 | };


回答:

你再试试在测试文件的顶部添加以下 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");

});


回答:

添加mock

jest.mock('vue-router', () => ({

useRouter: () => ({

push: jest.fn()

}),

}));

以上是 Vue3 + @vue/test-utils@next + VueRouter4 + Jest 单元测报错? 的全部内容, 来源链接: utcz.com/p/933956.html

回到顶部