Vue 路由器的注入在开玩笑单元测试期间失败



在一个带有Composition API(和Vue 3)的.vue文件中,设置路由器:

const router = useRouter()

在jest测试中挂载.vue文件:

const wrapper = mount(Lookup)

执行时产生:

console.warn
[Vue warn]: injection "Symbol([vue-router]: router)" not found.
at <Anonymous ref="VTU_COMPONENT" >
at <VTUROOT>

模拟结果相同:

useRouter().push = jest.fn()

设置提供相同输出的结果:

import { useRouter } from 'vue-router'
...
const wrapper = mount(Lookup, {
global: {
plugins: [useRouter],
provide: {
router: {},
},
},
})

这个解决方案允许我在Jest中模拟useRouter()。注意useRouter()是使用vue-router的唯一方法,因为this不可用:

const routerPushMock = jest.fn();
jest.mock('vue-router', () => ({
useRouter: () => ({
push: routerPushMock,
}),
}));
test('...', async () => {
const wrapper = mount(vueFile)
...

如果有人另外有这个错误

babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.

我建议这样写

const mockPush = jest.fn();
jest.mock('vue-router', () => ({
useRouter: () => ({
push: mockPush,
}),
}));

将其命名为mockPush(mockXYZ)很重要,因为根据:https://github.com/facebook/jest/issues/2567这个特定的命名是一个逃生舱口。

最新更新