在 jest.config.js 中:
setupFiles: ['<rootDir>/jest.init.js'],
Run Code Online (Sandbox Code Playgroud)
在 jest.init.js 中:
jest.mock('xxx/layout', () => ({
...
isMobile: false,
...
}))
Run Code Online (Sandbox Code Playgroud)
因此,在从 'xxx/layout' 导入 isMobile 的所有测试中,isMobile 将为 false
现在我尝试在一些测试中覆盖 isMobile,如下所示:
jest.mock('xxx/layout', () => ({ isMobile: true }))
isMobile.mockImplementation(() => true)
Run Code Online (Sandbox Code Playgroud)
但这不起作用!
这样做的好方法是什么?
您必须在第二次模拟后再次重新导入模块:在测试文件中:
test('Test', () => {
jest.mock('xxx/layout', () => ({ isMobile: true }))
const layout = require('xxx/layout'); // require the new mock
// run your test here
});
Run Code Online (Sandbox Code Playgroud)
当 Jest 设置测试环境时,会运行安装文件。您可以看到如下所示的作业顺序:
jest.init.js、嘲笑xxx/layout;| 归档时间: |
|
| 查看次数: |
3375 次 |
| 最近记录: |