【问题标题】:Vue router's injection fails during a Jest unit testVue 路由器的注入在 Je​​st 单元测试期间失败
【发布时间】:2021-10-16 04:40:42
【问题描述】:

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

const router = useRouter()

在开玩笑测试中挂载 .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: {},
    },
  },
})

【问题讨论】:

  • useRouter 不是插件,因此不应在global.plugins 中。显示您在组件中使用 useRouter() 的更多上下文。
  • @tony19 useRouter() 在本示例的组件中完全未使用。仅当 Jest 挂载它时,组件内的声明才会中断。如果我在组件中添加对它的使用(这不会影响 Jest 的当前结果),它会在组件中按预期工作。
  • 没有足够的上下文来重现问题。你能分享一个复制的链接吗?

标签: vue.js jestjs vue-router


【解决方案1】:

此解决方案允许我在 Jest 中模拟 useRouter()。请注意,useRouter() 是使用 vue-router 进行组合 API 的唯一方法,因为 this 不可用:

const routerPushMock = jest.fn();

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

test('...', async () => {
  const wrapper = mount(vueFile)
  ...

【讨论】:

  • 对于像我这样战斗了 3 个小时的人来说,需要注意的非常重要的一点是,你不能将 jest.mock() 放在 describe() 或 test() 中,它不会不能这样工作。似乎 jest.mock() 应该在规范文件的根目录中。
  • 你的解决方案对我有用,谢谢 :)
  • 出于某种原因,编写“jest.mock”似乎也很重要。把 "import mock = jest.mock" 然后 "mock('vue-router', ...)" 对我不起作用。我需要专门调用“jest.mock('vue-router', ...)”。
【解决方案2】:

如果有人还有这个错误

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 这个特定的命名是一个逃生舱口。

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多