我在 Jest 单元测试中有一个虚拟 javascript 文件,路径为“/widgets/1.0.js”。我模拟了 fs 模块来模拟它的存在。
现在我想动态加载它以调用方法“foo()”。我认为这将是使用虚拟模拟的情况:
index.test.js
jest.mock('/widgets/1.0.js', () => {foo: jest.fn(() => {console.log('foo!')})}, {virtual: true});
调用模拟的代码:
index.js
let module = require('/widgets/1.0.js');
module.foo();
当我运行测试时:
Cannot find module '/widgets/1.0.js' from 'index.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:151:17)
at processWidgets (src/index.js:115:2418)
at Object.<anonymous> (src/__tests__/index.test.js:99:73)
我觉得应该是可以的。有什么想法吗?
谢谢!
最佳答案
模块路径似乎有问题。这有效:
index.test.js
jest.mock('1.0', () => {
return {
foo: () => {return 42;}
}
}, {virtual: true});
index.js
const module = require('1.0');
let retval = module.foo();
console.log('retval: ', retval);
如果我使用“/widgets/1.0”,则不会。希望它有帮助..
关于javascript - 我如何在 Jest 中模拟动态加载的虚拟模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40682385/