Javascript 如何模拟动态加载的虚拟模块?

Javascript 如何模拟动态加载的虚拟模块?,javascript,unit-testing,mocking,virtual,jestjs,Javascript,Unit Testing,Mocking,Virtual,Jestjs,我在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

我在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.js'中找到模块'/widgets/1.0.js'
在Resolver.resolveModule(node_modules/jest resolve/build/index.js:151:17)
在processWidgets(src/index.js:115:2418)
反对。(src/_; tests\u__;/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',它不会。希望有帮助。

模块路径似乎有问题。这项工作:

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',它不会。希望对您有所帮助。

请记住,在您的第一个实现中,模拟函数没有返回任何内容,可能是错误。请记住,在您的第一个实现中,模拟函数没有返回任何内容,可能是错误