Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Easy monkey-patching for CodeRoad

License

NotificationsYou must be signed in to change notification settings

ShMcK/rewire-coderoad

Repository files navigation

Easy dependency injection for node.js unit testing.

Build StatusDependency StatusCoverage StatusGittip Donate Button

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 likeprocess
  • leak private variables
  • override variables within the module.

rewire doesnot load the file and eval the contents to emulate node's require mechanism. In fact it uses node's ownrequire to load the module. Thus your module behaves exactly the same in your test environment as under regularcircumstances (except your modifications).

Good news to all caffeine-addicts: rewire works also withCoffee-Script. Note that in thiscase CoffeeScript needs to be listed in your devDependencies.

If you want to use rewire also on the client-side take a look atclient-side bundlers

npm status


Introduction

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.js

varrewire=require("rewire");varmyModule=rewire("../lib/myModule.js");

rewire acts exactly like require. Just with 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

Caveats

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.

Changing globals
Be careful, if you do something like this you'll change your global console instance.

myModule.__set__("console.log",function(){/* be quiet */});

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.


API

rewire(filename: String): rewiredModule

Returns a rewired version of the module found atfilename. Userewire() exactly likerequire().

rewiredModule.__set__(name: String, value: *): Function

Sets the internal variablename to the givenvalue. Returns a function which can be called to revert the change.

rewiredModule.__set__(obj: Object): Function

Takes all enumerable keys ofobj as variable names and sets the values respectively. Returns a function which can be called to revert the change.

rewiredModule.__get__(name: String): *

Returns the private variable with the givenname.

rewiredModule.__with__(obj: Object): Function<callback: Function>

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.


##Client-Side Bundlers

###webpackSeerewire-webpack

###browserifyIf you're using browserify and want to use rewire with browserifyplease let me know.


##License

MIT

About

Easy monkey-patching for CodeRoad

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript99.9%
  • CoffeeScript0.1%

[8]ページ先頭

©2009-2025 Movatter.jp