rewire
Dependency injection for node.js applications.
rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may
- introduce mocks for other modules
- leak private variables
- 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).
Debugging is fully supported.
Furthermore rewire comes also with support for browserify. Thus you can mock your modules in the browser as well.
Installation
npm install rewire
For older node versions:
rewire is tested with node 0.6.x - 0.7.x. I recommend to run the unit tests via mocha
in the rewire-folder before using rewire with older node versions.
Use with browserify:
var b = require("browserify")({debug: true});
b.use(require("rewire").browserify);
Examples
var rewire = require("rewire");
var myModule = rewire("../lib/myModule.js");
myModule.__set__("myPrivateVar", 123);
myModule.__get__("myPrivateVar");
myModule.__set__("fs", {
readFile: function (path, encoding, cb) {
cb(null, "Success!");
}
});
myModule.readSomethingFromFileSystem(function (err, data) {
console.log(data);
});
myModule === require("./myModule.js");
myModule.__set__({
fs: fsMock,
http: httpMock,
someOtherVar: "hello"
});
myModule.__set__({
console: {
log: function () { }
},
process: {
argv: ["testArg1", "testArg2"]
}
});
myModule.__set__("console.log", function () { });
assert.ok(myModule.__get__("currentState") === "idle");
rewire("./myModule.js") === require("./myModule.js");
rewire("./myModule.js", false) === require("./myModule.js");
rewire("./myModule.js") === rewire("./myModule.js");
rewire.reset();
##API
rewire(filename, cache): {RewiredModule}
-
{!String} filename:
Path to the module that shall be rewired. Use it exactly like require().
-
{Boolean=true} cache (optional):
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.
rewire.reset()
Removes all rewired modules from require.cache
. Every require()
will now return the original module again.
RewiredModule.__set__(name, value)
RewiredModule.__set__(env)
- {!Object} env:
Takes all keys as variable names and sets the values respectively.
RewiredModule.__get__(name): {∗}
Returns the private variable.
Credits
This module is inspired by the great injectr-module.