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 'README.md')
-rw-r--r--README.md176
1 files changed, 72 insertions, 104 deletions
diff --git a/README.md b/README.md
index 4826178..69c80b8 100644
--- a/README.md
+++ b/README.md
@@ -2,12 +2,12 @@ rewire
=====
**Dependency injection for node.js applications**.
-rewire allows you to modify the behaviour of modules for better unit testing. You may
+rewire adds a special setter and getter that allow you to modify the behaviour of modules
+for better unit testing. You may
- introduce mocks for other modules
- leak private variables
-- override variables within the module
-- inject your own scripts
+- override variables within the module.
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).
@@ -22,8 +22,7 @@ Installation
`npm install rewire`
**For older node versions:**<br />
-rewire is tested with node 0.6.x. I recommend to run the unit tests via `mocha` in the rewire-folder before
-using rewire with older node versions.
+rewire is tested with node 0.6.x. I recommend to run the unit tests via `mocha` in the rewire-folder before using rewire with older node versions.
-----------------------------------------------------------------
<br />
@@ -34,72 +33,77 @@ Examples
```javascript
var rewire = require("rewire");
-// rewire acts exactly like require when omitting all other params
-rewire("./myModuleA.js") === require("./myModuleA.js"); // = true
-```
-### Mocks
-```javascript
-// You can introduce your own mocks for modules that are required:
-rewiredModule = rewire("./myModuleA.js", {
- "fs": {
- readFile: function (path, encoding, cb) { cb(null, "Success!"); }
- },
- "../path/to/moduleB.js": myMockForModuleB
+// rewire acts exactly like require.
+var myRewiredModule = rewire("../lib/myModule.js");
+myRewiredModule === require("../lib/myModule.js"); // = true
+
+
+// Your module will now export a special setter and getter for private variables.
+myModule.__set__("myPrivateVar", 123);
+myModule.__get__("myPrivateVar"); // = 123
+
+
+// This allows you to mock almost everything within the module e.g. the fs-module.
+// Just pass the variable name as first parameter and your mock as second.
+myModule.__set__("fs", {
+ readFile: function (path, encoding, cb) {
+ cb(null, "Success!");
+ }
+});
+myModule.readSomethingFromFileSystem(function (err, data) {
+ console.log(data); // = Success!
});
-// The rewired module will now use your mocks instead of fs
-// and moduleB.js. Just make sure that the path is exactly as
-// in myModuleA.js required.
-```
-### Injections
-```javascript
-// You can inject your own mocks for internal or global objects.
-// These injections are only visible within the module.
-rewiredModule = rewire("./myModuleA.js", null, {
+
+// All later requires will now return the module with the mock.
+myModule === require("./myModule.js"); // = true
+
+
+// You can set different variables with one call.
+myModule.__set__({
+ fs: fsMock,
+ http: httpMock,
+ someOtherVar: "hello"
+});
+
+
+// You may also override globals. These changes are only within the module,
+// so you don't have to be afraid that other modules are influenced by your mock.
+myModule.__set__({
console: {
log: function () { /* be quiet */ }
},
- process: { argv: ["some", "other", "args"] },
- __filename: "some/other/dir"
+ process: {
+ argv: ["testArg1", "testArg2"]
+ }
});
-// This will inject
-// var console = {log: function () { /* be quiet */ }};
-// var process = {argv: ["some", "other", "args"]};
-// var __filename = "some/other/dir";
-// at the end of the module.
-// You can also pass a script to inject at the end
-rewiredModule = rewire("./myModuleA.js", null, "console.log('hello');");
-// This will print "hello" when the module loads
-```
+// But be careful, if you do something like this you'll change your global
+// console instance.
+myModule.__set__("console.log", function () { /* be quiet */ });
-### Leaks
-```javascript
-// You can expose private variables for unit tests
-rewiredModule = rewire("./myModuleA.js", null, null, ["myVar1", "myVar2");
-// This will inject
-// module.exports.__ = {myVar1: myVar1, myVar2: myVar2}
-// at the end of the module.
+// By getting private variables you can test for instance if your
+// module is in a specific state
+assert.ok(myModule.__get__("currentState") === "idle");
-// You can access now your private variables under the special.__-object
-console.log(rewiredModule.__.myVar1);
-console.log(rewiredModule.__.myVar2);
-```
-### Cache
-```javascript
-// You can disable caching of the rewired module. Any require()-calls will
-// now return the original module again instead of the rewired.
-// Caching is enabled by default.
-rewire("./myModuleA.js", null, null, null, false) === require("./myModuleA.js");
-// = false
+// You can also disable caching when loading the rewired module. All
+// subsequent calls of require() will than return the original module again.
+rewire("./myModule.js", false) === require("./myModule.js"); // = false
+
+
+// Every call of rewire returns a new instance and overwrites the old
+// one in the module cache.
+rewire("./myModule.js") === rewire("./myModule.js"); // = false
-// You can also delete all rewired modules from the cache by one call.
+
+// If you want to remove all your rewired modules from the
+// cache just call rewire.reset().
+// Do this before every unit test to ensure a clean testing environment.
rewire.reset();
-// You should call this after every unit test to ensure a clean test environment.
```
-----------------------------------------------------------------
@@ -107,73 +111,37 @@ rewire.reset();
##API
-**rewire(***filename, mocks, injections, leaks, cache***)**
+**rewire(***filename, cache***): {RewiredModule}**
- *{!String} filename*: <br/>
Path to the module that shall be rewired. Use it exactly like require().
-- *{Object} mocks (optional)*: <br/>
-An object with module mocks. Keys should reflect the required path of the module.
-
-- *{Object|String} injections (optional)*: <br />
-If you pass an object, all keys of the object will be `var`s within the module. You can also eval a string.
-
-- *{Array&lt;String&gt;} leaks (optional)*: <br/>
-An array with variable names that should be exported. These variables are accessible via `myModule.__`.
-
- *{Boolean=true} cache (optional)*: <br />
Indicates whether the rewired module should be cached by node so subsequent calls of `require()` will
return the rewired module. Further calls of `rewire()` will always overwrite the cache.
-Returns the rewired module.
-
**rewire.reset()**
Removes all rewired modules from `require.cache`. Every `require()` will now return the original module again.
------------------------------------------------------------------
-<br />
+**RewiredModule.&#95;&#95;set&#95;&#95;(***name, value***)**
-## Please note
-### Keys should be exactly the 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}`.
+- *{!String} name*: <br/>
+Name of the variable to set. The variable should be a global or defined with `var` in the top-level
+scope of the module.
-### 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.
+- *{&lowast;} value*: <br/>
+The value to set
-Imagine `rewire("./myModule.js", null, {console: null});`:
+**RewiredModule.&#95;&#95;set&#95;&#95;(***env***)**
-```javascript
-console.log("Hello"); // ouch, that won't work. console is undefined at this point because of hoisting
-
-// End of module ///////////////
-// rewire will inject here
-var console = null;
-```
-
-### Leaks are executed at the end of the module.
-All variables, that are [copied by value](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language)
-will not be updated anymore.
-
-A good approach to solve this would be:
-
-```javascript
-var myLeaks = {};
-
-module.exports = function (someValue) {
- myLeaks.someValue = someValue;
-};
-```
+- *{!Object} env*: <br/>
+Takes all keys as variable names and sets the values respectively.
-And then: ```rewire("myModuleA.js", null, null, ["myLeaks"]);```
+**RewiredModule.&#95;&#95;get&#95;&#95;(***name***): {&lowast;}**
-Because ```myLeaks``` is defined at the end of the module, you're able to access the leak object and all leaks that
-are attached to it later during runtime.
+Returns the private variable.
-### Call rewire.reset() after every unit test
-All ```require()```s will now return the original module again.
-----------------------------------------------------------------
<br />