英文:
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() }
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论