- Notifications
You must be signed in to change notification settings - Fork128
Easy monkey-patching for node.js unit tests
License
jhnns/rewire
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Easy monkey-patching for node.js unit tests
rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may
- inject mocks for other modules or globals like
process - inspect private variables
- override variables within the module.
Please note: The current version of rewire is only compatible with CommonJS modules. SeeLimitations.
npm install rewire
Imagine you want to test this module:
// lib/myModule.js// With rewire you can change all these variablesvarfs=require("fs"),path="/somewhere/on/the/disk";functionreadSomethingFromFileSystem(cb){console.log("Reading from file system ...");fs.readFile(path,"utf8",cb);}exports.readSomethingFromFileSystem=readSomethingFromFileSystem;
Now within your test module:
// test/myModule.test.jsvarrewire=require("rewire");varmyModule=rewire("../lib/myModule.js");
rewire acts exactly like require. With just one difference: Your module will now export a special setter and getter for private variables.
myModule.__set__("path","/dev/null");myModule.__get__("path");// = '/dev/null'
This allows you to mock everything in the top-level scope of the module, like the fs module for example. Just pass the variable name as first parameter and your mock as second.
varfsMock={readFile:function(path,encoding,cb){expect(path).to.equal("/somewhere/on/the/disk");cb(null,"Success!");}};myModule.__set__("fs",fsMock);myModule.readSomethingFromFileSystem(function(err,data){console.log(data);// = Success!});
You can also set multiple variables with one call.
myModule.__set__({fs:fsMock,path:"/dev/null"});
You may also override globals. These changes are only within the module, so you don't have to be concerned that other modules are influenced by your mock.
myModule.__set__({console:{log:function(){/* be quiet */}},process:{argv:["testArg1","testArg2"]}});
__set__ returns a function which reverts the changes introduced by this particular__set__ call
varrevert=myModule.__set__("port",3000);// port is now 3000revert();// port is now the previous value
For your convenience you can also use the__with__ method which reverts the given changes after it finished.
myModule.__with__({port:3000})(function(){// within this function port is 3000});// now port is the previous value again
The__with__ method is also aware of promises. If a thenable is returned all changes stay until the promise has either been resolved or rejected.
myModule.__with__({port:3000})(function(){returnnewPromise(...);}).then(function(){// now port is the previous value again});// port is still 3000 here because the promise hasn't been resolved yet
Babel's ES module emulation
During the transpilation step from ESM to CJS modules, Babel renames internal variables. Rewire will not work in these cases (see#62). Other Babel transforms, however, should be fine. Another solution might be switching tobabel-plugin-rewire.
Variables inside functions
Variables inside functions can not be changed by rewire. This is constrained by the language.
// myModule.js(function(){// Can't be changed by rewirevarsomeVariable;})()
Modules that export primitives
rewire is not able to attach the__set__- and__get__-method if your module is just exporting a primitive. Rewiring does not work in this case.
// Will throw an error if it's loaded with rewire()module.exports=2;
Globals with invalid variable names
rewire imports global variables into the local scope by prepending a list ofvar declarations:
varsomeGlobalVar=global.someGlobalVar;
IfsomeGlobalVar is not a valid variable name, rewire just ignores it.In this case you're not able to override the global variable locally.
Special globals
Please be aware that you can't rewireeval() or the global object itself.
Returns a rewired version of the module found atfilename. Userewire() exactly likerequire().
Sets the internal variablename to the givenvalue. Returns a function which can be called to revert the change.
Takes all enumerable keys ofobj as variable names and sets the values respectively. Returns a function which can be called to revert the change.
Returns the private variable with the givenname.
Returns a function which - when being called - setsobj, executes the givencallback and revertsobj. Ifcallback returns a promise,obj is only reverted after the promise has been resolved or rejected. For your convenience the returned function passes the received promise through.
Difference to require()
Every call of rewire() executes the module again and returns a fresh instance.
rewire("./myModule.js")===rewire("./myModule.js");// = false
This can especially be a problem if the module is not idempotentlike mongoose models.
Globals are imported into the module's scope at the time of rewiring
Since rewire imports all gobals into the module's scope at the time of rewiring, property changes on theglobal object after that are not recognized anymore. This is aproblem when using sinon's fake timersafter you've calledrewire().
Dot notation
Although it is possible to use dot notation when calling__set__, it is strongly discouraged in most cases. For instance, writingmyModule.__set__("console.log", fn) is effectively the same as just writingconsole.log = fn. It would be better to write:
myModule.__set__("console",{log:function(){}});
This replacesconsole just insidemyModule. That is, because rewire is usingeval() to turn the key expression into an assignment. Hence, callingmyModule.__set__("console.log", fn) modifies thelog function on theglobalconsole object.
MIT
About
Easy monkey-patching for node.js unit tests
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.