简体   繁体   中英

Mock require function in Jest

I am trying to mock require using Jest because I am working in a plugin system for electron that will also use NPM for resolving dependencies. I need to then be able to mock require inside nodejs to be able to test something similar to the next logic.

const load = (installPath, pluginsName, extensionPoint) => {
    require.main.paths.push(`${installPath}/node_modules`)
    pluginsName.forEach(pluginName => {
        let plugin = require(pluginName)
        plugin.onLoad(extensionPoint)
    });
}
module.exports = { load }

Is there any simple way of doing this?. As require is not a global , is there is any other way than wrapping and injecting it to test the logic?

As explained in this answer , it's possible to replace require in particular module by evaluating it with custom require , similarly to how Node does this internally :

const Module = require('module');
const vm = require('vm');

const childModuleAbsPath = path.resolve('./foo/bar.js');
const childModuleBody = fs.readFileSync(childModuleAbsPath);
const childModuleObj = { exports: {} };
const { dir: childModuleDirname, base: childModuleFilename } = path.parse(childModuleAbsPath);
const childRequire = jest.fn().mockReturnValue(...);

vm.runInThisContext(Module.wrap(childModuleBody))(
  childModuleObj.exports,
  childRequire,
  childModuleObj,
  childModuleDirname,
  childModuleFilename
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM