Alvaro Lorente
Alvaro Lorente

Reputation: 3084

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?

Upvotes: 0

Views: 1842

Answers (1)

Estus Flask
Estus Flask

Reputation: 222568

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
);

Upvotes: 1

Related Questions