Skip to content

Commit

Permalink
Add an option to intercept and rewire nested requires
Browse files Browse the repository at this point in the history
Follow up to jhnns#73
  • Loading branch information
airhorns committed Jun 29, 2021
1 parent 90e781f commit 4a8faf0
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/index.js
Expand Up @@ -7,8 +7,8 @@ var rewireModule = require("./rewire.js");
* @param {!String} filename Path to the module that shall be rewired. Use it exactly like require().
* @return {*} the rewired module
*/
function rewire(filename) {
return rewireModule(module.parent, filename);
function rewire(filename, rewireNestedRequires) {
return rewireModule(module.parent, filename, rewireNestedRequires);
}

module.exports = rewire;
Expand Down
18 changes: 17 additions & 1 deletion lib/rewire.js
Expand Up @@ -8,7 +8,7 @@ var Module = require("module"),
/**
* Does actual rewiring the module. For further documentation @see index.js
*/
function internalRewire(parentModulePath, targetPath) {
function internalRewire(parentModulePath, targetPath, rewireNestedRequires) {
var targetModule,
prelude,
appendix,
Expand All @@ -28,6 +28,22 @@ function internalRewire(parentModulePath, targetPath) {
// We prepend a list of all globals declared with var so they can be overridden (without changing original globals)
prelude = getImportGlobalsSrc();

// If asked, intercept require calls when evaluating the rewired module to rewire those inner requires
if (rewireNestedRequires) {
targetModule.__rewire__ = internalRewire;

prelude += `
const __oldRequire = require;
var require = function(path) {
if (module.__rewire__) {
return module.__rewire__(module.parent, path);
} else {
return __oldRequire(path);
}
};
`
}

// Wrap module src inside IIFE so that function declarations do not clash with global variables
// @see https://github.com/jhnns/rewire/issues/56
prelude += "(function () { ";
Expand Down
13 changes: 13 additions & 0 deletions testLib/sharedTestCases.js
Expand Up @@ -408,4 +408,17 @@ module.exports = function () {
}).to.throwException(/^Assignment to constant variable at .+?wrongConstModule\.js:4:1$/);
});

it("should not rewire nested requires by default", function () {
const a = rewire('./moduleA')
const b = rewire('./moduleB')

expect(a.someOtherModule.date).to.equal(b.someOtherModule.date)
})

it("should rewire nested requires by default", function () {
const a = rewire('./moduleA', true)
const b = rewire('./moduleB', true)

expect(a.someOtherModule.date).not.to.equal(b.someOtherModule.date)
})
};
1 change: 1 addition & 0 deletions testLib/someOtherModule.js
Expand Up @@ -5,3 +5,4 @@ __filename = "/test/testModules/someOtherModule.js";
exports.fs = {};
exports.filename = __filename;
exports.name = "somOtherModule";
exports.date = new Date();

0 comments on commit 4a8faf0

Please sign in to comment.