我想做类似的事情
[
{ path: 'path1', comp: () => <div>comp 1</div> },
{ path: 'path2', comp: () => <div>comp 2</div> },
].forEach(({ path, comp }) => {
jest.mock(path, {
__esModule: true,
default: comp
})
});
但我收到以下错误:'jest.mock()'的模块工厂不允许引用任何超出范围的变量。
知道如何做到这一点吗?
我也尝试过使用简单的 for 循环,但遇到了相同的错误。
最佳答案
jest.mock
确实很棘手,因为它应该在任何 import
之前执行。实际上运行。所以有some limitations :
A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'. It's up to you to guarantee that they will be initialized on time!
即使重命名后我也不知道为什么 comp
至mockComp
代码失败,直到我删除 __esmodule: true
。所以这传给了我:
[
{ path: 'comp1', mockComp: () => <div>1</div> },
{ path: 'comp2', mockComp: () => <span>2</span> },
].forEach(({ path, mockComp }) => {
jest.mock(path, () => mockComp);
});
无论如何,即使你发现模块是 esModule
并且代码已通过,我仍然相信有单独的 jest.mock()
每个模块比配置迭代更易于维护。至少添加、删除和混合内联模拟与自动模拟真的很容易jest.mock('module1');
依赖于 __mocks__
中的代码文件夹(与 forEach
和配置对象的方法不同)
关于javascript - Jest 一次性模拟多个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59733277/