- Notifications
You must be signed in to change notification settings - Fork0
Easy monkey-patching for CodeRoad
License
ShMcK/rewire-coderoad
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Dependency injection for node.js applications.
rewire allows you to modify the behaviour of modules for better unit testing. You may
- provide mocks for other modules
- leak private variables
- override variables within the module
- inject your own scripts
rewire doesnot 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.
npm install rewire
varrewire=require("rewire"),rewiredModule;// Default////////////////////////////////// rewire acts exactly like require when omitting all other paramsrewire("./myModuleA.js")===require("./myModuleA.js");// = true// Mocks////////////////////////////////varmockedModuleB={},mockedFs={},mocks={"fs":mockedFs,"path/to/moduleB.js":mockedModuleB};// 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.rewiredModule=rewire("./myModuleA.js",mocks);// Injections////////////////////////////////varinjections={console:{log:function(){/* be quiet */}},process:{argv:["someArgs"]},__filename:"some/other/dir"};// 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 modulerewiredModule=rewire("./myModuleA.js",null,injections);// You can also pass a script to injectrewiredModule=rewire("./myModuleA.js",null,"console.log('hellooo');");// prints "hellooo"// Leaks////////////////////////////////varleaks=["myPrivateVar1","myPrivateVar2"];// rewire exports variables under the special "__"-object.rewiredModule=rewire("./myModuleA.js",null,null,leaks);rewiredModule.__.myPrivateVar1;// returns former private myPrivateVar1rewiredModule.__.myPrivateVar2;// returns former private myPrivateVar2// Cache////////////////////////////////// By disabling the module cache the rewired module will not be cached.// 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");// = true// This removes all rewired modules from require.cache.rewire.reset();// IMPORTANT: You should call this before every unit test to ensure// a clean test environment.
##API
rewire(filename, mocks, injections, leaks, cache)
{!String} filename:
Path to the module that shall be rewired. Use it exactly like require().{Object} mocks (optional):
An object with mocks.{Object|String} injections (optional):
If you pass an object, all keys of the object will bevar
s within the module. You can also eval a string.{Array<String>} leaks (optional):
An array with variable names that should be exported. These variables are accessible viamyModule.__
.{Boolean=true} cache (optional):
Indicates whether the rewired module should be cached by node so subsequent calls ofrequire()
willreturn the rewired module. Further calls ofrewire()
will always overwrite the cache.
Returns the rewired module.
rewire.reset()
Removes all rewired modules fromrequire.cache
. Everyrequire()
will now return the original module again.
Keys should be the exactly the same like they're required in the target module.So if you writerequire("../../myModules/myModuleA.js")
you need to pass{"../../myModules/myModuleA.js": myModuleAMock}
.
All scripts are injected at the end of the module. So if there is any code in your modulethat is executed duringrequire()
, your injected variables will be undefined at this point.
Imaginerewire("./myModule.js", null, {console: null});
:
console.log("Hello");// ouch, that won't work. console is undefined at this point because of hoisting// End of module ///////////////// rewire will inject herevarconsole=null;
Leaks are executed at the end of the module. If avar
is undefined at this point youwon't be able to access the leak (becauseundefined
-values arecopied by value).A good approach to this is:
varmyLeaks={};module.exports=function(someValue){myLeaks.someValue=someValue;};// End of module ///////////////// rewire will inject heremodule.exports.__={myLeaks:myLeaks};
BecausemyLeaks
is defined at the end of the module, you're able to access the leak object and all leaks thatare attached to it later during runtime. Because myLeaks is not exposed under regular circumstances yourmodule interface stays clean.
You should call this before every unit test to ensure a clean test environment.
This module is inspired by the greatinjectr-module.
(The MIT License)
Copyright (c) 2012 Johannes Ewald <mail@johannesewald.de>
Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the'Software'), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall beincluded 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 OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About
Easy monkey-patching for CodeRoad
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.
Languages
- JavaScript99.9%
- CoffeeScript0.1%