diff options
author | Johannes <mail@johannesewald.de> | 2012-06-04 02:23:27 +0400 |
---|---|---|
committer | Johannes <mail@johannesewald.de> | 2012-06-04 02:23:27 +0400 |
commit | b4b2794f5a5e5977e048ff777ac53263144126e6 (patch) | |
tree | 11213db4acbb4bd220069bd426b83d9739339379 /lib/rewire.js | |
parent | d4eea33555f4e67be674c046ff1d1a9a460af94a (diff) |
changed repo-name to rewire
Diffstat (limited to 'lib/rewire.js')
-rw-r--r-- | lib/rewire.js | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/lib/rewire.js b/lib/rewire.js new file mode 100644 index 0000000..0f96e4d --- /dev/null +++ b/lib/rewire.js @@ -0,0 +1,65 @@ +"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");
+
+function restoreOriginalWrappers() {
+ Module.wrapper[1] = nodeWrapper1;
+}
+
+function rewire(parentModule, filename, mocks, injections, leaks, cache) {
+ var testModule,
+ nodeRequire,
+ wrapperExtensions = "";
+
+ 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") {
+ 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 = 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 = rewire;
\ No newline at end of file |