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:
-rw-r--r--README.md85
-rw-r--r--lib/getInjectionSrc.js15
-rw-r--r--lib/getLeakingSrc.js9
-rw-r--r--lib/index.js21
-rw-r--r--lib/rewire.js9
-rw-r--r--test/rewire.test.js11
6 files changed, 134 insertions, 16 deletions
diff --git a/README.md b/README.md
index 8462cc8..11fe36b 100644
--- a/README.md
+++ b/README.md
@@ -7,15 +7,21 @@ rewire allows you to modify the behaviour of modules for better unit testing. Yo
- provide mocks for other modules
- leak private variables
- override variables within the module
-- inject scripts
+- inject your own scripts
-rewire does **not** load the file and eval it to emulate node's require mechanism. In fact it uses node's require to load the module. Thus your module behaves exactly the same in your test environment as under regular circumstances (except your modifications).
+rewire does **not** load the file and eval the contents to emulate node's require mechanism. In fact it uses node's own require to load the module. Thus your module behaves exactly the same in your test environment as under regular circumstances (except your modifications).
+
+**Debugging is fully supported.**
+
+-----------------------------------------------------------------
Installation
------------
```npm install rewire```
+-----------------------------------------------------------------
+
Examples
--------
@@ -28,6 +34,8 @@ var rewire = require("rewire"),
// rewire acts exactly like require when omitting all other params
rewiredModule = rewire("./myModuleA.js");
+
+
// Mocks
////////////////////////////////
var mockedModuleB = {},
@@ -35,10 +43,11 @@ var mockedModuleB = {},
"path/to/moduleB.js": mockedModuleB
};
-// the rewired module will now use your mock instead of moduleB.js.
+// The rewired module will now use your mock instead of moduleB.js.
rewiredModule = rewire("./myModuleA.js", mocks);
+
// Injections
////////////////////////////////
var injections = {
@@ -49,13 +58,79 @@ var injections = {
__filename: "some/other/dir"
};
-// overrides all given variables within the module
+// This will inject
+// var console = {log: function () { /* be quiet */ }};
+// var process = {argv: ["someArgs"] };
+// var __filename = "some/other/dir";
+// at the bottom of the module.
+// This way you can override private variables within the module
rewiredModule = rewire("./myModuleA.js", null, injections);
-// you can also pass a script to inject
+
+// You can also pass a script to inject
rewiredModule = rewire("./myModuleA.js", null, "console.log('hellooo');");
+
// Leaks
////////////////////////////////
+var leaks = ["myPrivateVar1", "myPrivateVar2"];
+
+// rewire exports variables under the special "__"-object.
+rewiredModule = rewire("./myModuleA.js", null, null, leaks);
+console.log(rewiredModule.__.myPrivateVar1);
+console.log(rewiredModule.__.myPrivateVar2);
+
+
+// Cache
+////////////////////////////////
+// By disabling the module cache the rewired module will not be cached.
+// Any later require()-calls within other modules will now return the original
+// module again instead of the rewired. Caching is enabled by default.
+rewiredModule = rewire("./myModuleA.js", null, null, null, false);
```
+
+-----------------------------------------------------------------
+
+##API
+
+**rewire(***filename, mocks\*, injections\*, leaks\*, cache=true*) \* = optional
+
+- *{!String} **filename***: Path to the module that shall be rewired. Use it exactly like require().
+- *{Object} **mocks***: An object with mocks. Keys should be the exactly same like they're required in the target module. So if you write ```require("../../myModules/myModuleA.js")``` you need to pass ```{"../../myModules/myModuleA.js": myModuleAMock}```.
+- *{Object|String} **injections***: If you pass an object, all keys of the object will be ```var```s within the module. You can also eval a string. **Please note**: All scripts are injected at the end of the module. So if there is any code in your module that is executed during ```require()```, your injected variables will be undefined at this point. For example: passing ```{console: {...}}``` will cause all calls of ```console.log()``` to throw an exception if they're executed during ```require()```.
+- *{Array<String>} **leaks***: An array with variable names that should be exported. These variables are accessible via ```myModule.__```
+- *{Boolean=true} **cache***: Indicates whether the rewired module should be cached by node so subsequent calls of ```require()``` will return the rewired module. Subsequent calls of ```rewire()``` will always overwrite the cache.
+
+-----------------------------------------------------------------
+
+## Credits
+
+This module is inspired by the great [injectr](https://github.com/nathanmacinnes/injectr "injectr")-module.
+
+-----------------------------------------------------------------
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2012 Johannes Ewald <mail@johannesewald.de>
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file
diff --git a/lib/getInjectionSrc.js b/lib/getInjectionSrc.js
index 67c15ec..74174d0 100644
--- a/lib/getInjectionSrc.js
+++ b/lib/getInjectionSrc.js
@@ -2,7 +2,16 @@
var toSrc = require("toSrc");
-function getMonkeyPatchSrc(obj) {
+/**
+ * Returns the source code for injecting vars.
+ *
+ * e.g.:
+ * "var console=123;"
+ *
+ * @param {Object} obj
+ * @return {String}
+ */
+function getInjectionSrc(obj) {
function walkObj(obj, level) {
var key,
value,
@@ -12,7 +21,7 @@ function getMonkeyPatchSrc(obj) {
if (obj.hasOwnProperty(key)) {
value = obj[key];
if (level === 0) {
- src += "var "; // on the top level, we need a var statement to override variables
+ src += "var "; // on the top level we need a var statement
}
src += key + "=" + toSrc(value, 9999) + ";";
}
@@ -25,4 +34,4 @@ function getMonkeyPatchSrc(obj) {
return walkObj(obj, 0);
}
-module.exports = getMonkeyPatchSrc; \ No newline at end of file
+module.exports = getInjectionSrc; \ No newline at end of file
diff --git a/lib/getLeakingSrc.js b/lib/getLeakingSrc.js
index c827411..8475908 100644
--- a/lib/getLeakingSrc.js
+++ b/lib/getLeakingSrc.js
@@ -1,5 +1,14 @@
"use strict"; // run code in ES5 strict mode
+/**
+ * Returns the source code that will leak private vars.
+ *
+ * e.g.:
+ * "exports.__ = {myPrivateVar: myPrivateVar};"
+ *
+ * @param {Array<String>} leaks
+ * @return {String}
+ */
function getLeakingSrc(leaks) {
var src = "exports.__ = {",
varName,
diff --git a/lib/index.js b/lib/index.js
index 097a7b8..321b65c 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -1,13 +1,26 @@
"use strict"; // run code in ES5 strict mode
-var rewire = require("./rewire.js");
+var rewireModule = require("./rewire.js");
-module.exports = function (request, mocks, injections, leaks, cache) {
+/**
+ * This function is needed to determine the calling parent module.
+ * Thus rewire acts exactly the same like require() in the test module.
+ *
+ * @param {!String} request Path to the module that shall be rewired. Use it exactly like require().
+ * @param {Object} mocks An object with mocks. Keys should be the exactly same like they're required in the target module. So if you write require("../../myModules/myModuleA.js") you need to pass {"../../myModules/myModuleA.js": myModuleAMock}.
+ * @param {Object} injections If you pass an object, all keys of the object will be vars within the module. You can also eval a string. Please note: All scripts are injected at the end of the module. So if there is any code in your module that is executed during require(), your injected variables will be undefined at this point. For example: passing {console: {...}} will cause all calls of console.log() to throw an exception if they're executed during require().
+ * @param {Array} leaks An array with variable names that should be exported. These variables are accessible via myModule.__
+ * @param {Boolean} cache Indicates whether the rewired module should be cached by node so subsequent calls of require() will return the rewired module. Subsequent calls of rewire() will always overwrite the cache.
+ * @return {*} the rewired module
+ */
+function rewire(request, mocks, injections, leaks, cache) {
delete require.cache[__filename]; // deleting self from module cache so the parent module is always up to date
if (cache === undefined) {
cache = true;
}
- return rewire(module.parent, request, mocks, injections, leaks, cache);
-}; \ No newline at end of file
+ return rewireModule(module.parent, request, mocks, injections, leaks, cache);
+}
+
+module.exports = rewire; \ No newline at end of file
diff --git a/lib/rewire.js b/lib/rewire.js
index 0f96e4d..6f1ac7d 100644
--- a/lib/rewire.js
+++ b/lib/rewire.js
@@ -10,7 +10,10 @@ function restoreOriginalWrappers() {
Module.wrapper[1] = nodeWrapper1;
}
-function rewire(parentModule, filename, mocks, injections, leaks, cache) {
+/**
+ * Does actual rewiring the module. For further documentation @see index.js
+ */
+module.exports = function doRewire(parentModule, filename, mocks, injections, leaks, cache) {
var testModule,
nodeRequire,
wrapperExtensions = "";
@@ -60,6 +63,4 @@ function rewire(parentModule, filename, mocks, injections, leaks, cache) {
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
+}; \ No newline at end of file
diff --git a/test/rewire.test.js b/test/rewire.test.js
index 41dff60..2df19e0 100644
--- a/test/rewire.test.js
+++ b/test/rewire.test.js
@@ -109,4 +109,15 @@ describe("#rewire", function () {
rewired.requireIndex();
expect(rewired.index.b).not.to.be(rewired);
});
+ it("should not influence the original node require if nothing has been required within the rewired module", function () {
+ var moduleCMock = {},
+ moduleB,
+ mocks = {
+ "../C/moduleC.js": moduleCMock
+ };
+
+ rewire("./testModules/C/moduleC.js", mocks); // nothing happens here because moduleC doesn't require anything
+ moduleB = require("./testModules/A/moduleA.js"); // if restoring the original node require didn't worked, the mock would be applied now
+ expect(moduleB.c).not.to.be(moduleCMock);
+ });
}); \ No newline at end of file