Vue3组合式API下Jest路由模拟测试报错:Cannot read properties of undefined
解决Vue3组合式API路由模拟测试报错:Cannot read properties of undefined (reading 'name')
问题原因
你的组件使用Vue Router组合式API的useRoute()获取路由实例,但测试代码仍采用选项式API的方式模拟$route。由于组合式API的useRoute()是通过依赖注入获取路由对象,而非直接访问组件实例的$route属性,这种模拟方式不会生效,导致route变量为undefined,访问route.name时触发报错。
解决方案
需要直接模拟vue-router中的useRoute函数,让它返回预设的路由对象。修改后的测试代码如下:
import { shallowMount } from "@vue/test-utils"; import { useRoute } from "vue-router"; import Subnav from "@/components/Navigation/Subnav.vue"; // 模拟vue-router的useRoute函数 jest.mock("vue-router", () => ({ useRoute: jest.fn() })); describe("Subnav", () => { describe("当用户在职位列表页时", () => { it("显示职位数量", () => { // 让useRoute返回预设的路由对象 useRoute.mockReturnValue({ name: "jobResults" }); const wrapper = shallowMount(Subnav, { global: { stubs: { FontAwesomeIcon: true, }, }, }); const jobCount = wrapper.find("[data-test='job-count']"); expect(jobCount.exists()).toBe(true); }); }); });
关键修改说明
- 用
jest.mock替换vue-router模块,将真实的useRoute函数替换为jest模拟函数 - 在测试用例中通过
useRoute.mockReturnValue()设置要返回的路由对象,确保组件调用useRoute()时能拿到预设的路由信息 - 移除原本无效的
global.mocks.$route配置
修改后,组件中的route变量会正确获取到模拟的路由对象,不会再出现undefined的情况,测试即可正常执行。
内容的提问来源于stack exchange,提问作者Tertiadecima
相关产品推荐
相关产品推荐

