我在这里看到有关嘲笑默认出口的问题,但我不认为这已经被问到:
在模拟正在测试的模块的依赖项的默认导出TypeError: (0 , _dependency.default) is not a function时,如果模块使用ES6 import语句导入依赖项,则测试套件无法运行,但是,如果模块使用require().default调用,则说明它成功.
根据我的理解,import module from location直接转换为const module = require(location).default,所以我很困惑为什么会发生这种情况.我宁愿保持我的代码风格一致,也不要require在原始模块中使用调用.
有办法吗?
使用mock测试文件:
import './modules.js';
import dependency from './dependency';
jest.mock('./dependency', () => {
return {
default: jest.fn()
};
});
// This is what I would eventually like to call
it('calls the mocked function', () => {
expect(dependency).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
Dependency.js
export default () => console.log('do something');
Run Code Online (Sandbox Code Playgroud)
module.js(不工作)
import dependency from './dependency.js';
dependency();
Run Code Online (Sandbox Code Playgroud)
module.js(工作)
const dependency …Run Code Online (Sandbox Code Playgroud)