在 Jest 单元测试期间,Vue 路由器的注入失败

Vue router's injection fails during a Jest unit test

在包含组合 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()

设置 provide 导致相同的输出:

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

这个解决方案允许我在 Jest 中模拟 useRouter()。请注意,useRouter() 是使用 vue-router 合成 API 的唯一方法,因为 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 这个特定的命名是一个逃生通道。