ReferenceError: 使用 vitest 时无法在初始化之前访问模拟。

huangapple go评论80阅读模式
英文:

ReferenceError: Cannot access mock before initialization when using vitest

问题

在我的测试文件顶部,我有:

const setExMock = vi.fn()

然后我模拟了Redis模块(这部分有效):

vi.mock('redis', () => {
  return {
    createClient: () => {
      return {
        connect: vi.fn(),
        get: vi.fn(),
        setEx: setExMock,
      }
    },
  }
})

然后我遇到了这个错误:

ReferenceError: Cannot access 'setExMock' before initialization

我为什么要这样做?因为我想在我的测试中检查setExMock是否以某些参数被调用。

我知道vitest会提升模拟,但我该如何做呢?我查看了文档但没有找到相关信息。

英文:

On the top of my test file, I have:

const setExMock = vi.fn()

Then I mock the Redis module (which works)

vi.mock('redis', () => {
  return {
    createClient: () => {
      return {
        connect: vi.fn(),
        get: vi.fn(),
        setEx: setExMock,
      }
    },
  }
})

Then I get the error:

> ReferenceError: Cannot access 'setExMock' before initialization

Why I'm doing this? Because I want to check on my tests if setExMock was called with some parameters.

I know that vitest hoistes the mock, but how can I do this? I looked at the documentation and haven't found anything.

答案1

得分: 0

发现解决方法,需要封装成一个提升的方法

const { setExMock } = vi.hoisted(() => {
  return { setExMock: vi.fn() }
})
英文:

Found the solution, it is necessary to wrap into a hoisted method

const { setExMock } = vi.hoisted(() => {
  return { setExMock: vi.fn() }
})

huangapple
  • 本文由 发表于 2023年8月4日 22:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定