1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
"use strict"; // run code in ES5 strict mode
var Module = require("module"),
nodeWrapper0 = Module.wrapper[0], // caching original wrapper
nodeWrapper1 = Module.wrapper[1],
getLeakingSrc = require("./getLeakingSrc.js"),
getInjectionSrc = require("./getInjectionSrc.js"),
rewiredModules = [];
function restoreOriginalWrappers() {
Module.wrapper[1] = nodeWrapper1;
}
/**
* Does actual rewiring the module. For further documentation @see index.js
*/
function rewire(parentModule, filename, mocks, injections, leaks, cache) {
var testModule,
nodeRequire,
wrapperExtensions = "";
function requireMock(path) {
restoreOriginalWrappers(); // we need to restore the wrappers now so we don't influence other modules
if (mocks && mocks.hasOwnProperty(path)) {
return mocks[path];
} else {
return nodeRequire.call(testModule, path); // node's require only works when "this" points to the module
}
}
// Checking params
if (typeof filename !== "string") {
throw new TypeError("Filename must be a string");
}
// Init vars
filename = Module._resolveFilename(filename, parentModule); // resolve full filename relative to the parent module
// Special support for older node versions that returned an array on Module._resolveFilename
// @see https://github.com/joyent/node/blob/865b077819a9271a29f982faaef99dc635b57fbc/lib/module.js#L319
if (Array.isArray(filename)) {
filename = filename[1];
}
testModule = new Module(filename, parentModule);
nodeRequire = testModule.require; // caching original node require
// Prepare module for injection
if (typeof injections === "object") {
wrapperExtensions += getInjectionSrc(injections);
} else if (typeof injections === "string") {
wrapperExtensions += injections;
}
// Prepare module for leaking private vars
if (Array.isArray(leaks)) {
wrapperExtensions += getLeakingSrc(leaks);
}
Module.wrapper[1] = wrapperExtensions + nodeWrapper1;
// Mocking module.require-function
testModule.require = requireMock;
// Loading module
testModule.load(testModule.id);
if (cache) {
require.cache[filename] = testModule;
rewiredModules.push(filename); // save in private cache for .reset()
}
restoreOriginalWrappers(); // this is only necessary if nothing has been required within the module
return testModule.exports;
}
rewire.reset = function () {
var i;
for (i = 0; i < rewiredModules.length; i++) {
delete require.cache[rewiredModules[i]];
}
rewiredModules = [];
};
module.exports = rewire;
|