Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/twbs/rewire.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'lib/trick.js')
-rw-r--r--lib/trick.js64
1 files changed, 64 insertions, 0 deletions
diff --git a/lib/trick.js b/lib/trick.js
new file mode 100644
index 0000000..36644be
--- /dev/null
+++ b/lib/trick.js
@@ -0,0 +1,64 @@
+"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"),
+ getMonkeyPatchSrc = require("./getMonkeyPatchSrc.js");
+
+function restoreOriginalWrappers() {
+ Module.wrapper[0] = nodeWrapper0;
+ Module.wrapper[1] = nodeWrapper1;
+}
+
+function trick(parentModule, filename, mocks, injections, leaks, cache) {
+ var testModule,
+ nodeRequire;
+
+ function requireTrick(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
+ testModule = new Module(filename, parentModule);
+ nodeRequire = testModule.require; // caching original node require
+
+ // Prepare module for injection
+ if (typeof injections === "object") {
+ Module.wrapper[0] = nodeWrapper0 + getMonkeyPatchSrc(injections);
+ } else if (typeof injections === "string") {
+ Module.wrapper[0] = nodeWrapper0 + injections;
+ }
+
+ // Prepare module for leaking private vars
+ if (Array.isArray(leaks)) {
+ Module.wrapper[1] = getLeakingSrc(leaks) + nodeWrapper1;
+ }
+
+ // Mocking module.require-function
+ testModule.require = requireTrick;
+ // Loading module
+ testModule.load(testModule.id);
+
+ if (cache) {
+ require.cache[filename] = testModule;
+ }
+
+ restoreOriginalWrappers(); // this is only necessary if nothing has been required within the module
+
+ return testModule.exports;
+}
+
+module.exports = trick; \ No newline at end of file