Finally, a solution to node.js dependency injection
npm install injectr
. Boom.
var injectr = require('injectr');
var myScript = injectr('./lib/myScript.js', {
fs : mockFs,
crypto : mockCrypto
});
Now when you require('fs')
or require('crypto')
in myScript.js, what you get
is mockFs
or mockCrypto
. It works with relative requires too. Just make
sure you make the property name exactly the same as what is required in the
file being tested.
Treat injectr like require
for your tests, with a second argument to pass
in your mocks. The only thing to note is that paths are relative to the
working directory, not to the file location as with require
.
injectr is under the MIT License. Fork it. Modify it. Pass it around.