Independence
Module dependency injection for easy and fast mocking.
Enables a module to quickly create clones of itself that have their dependencies mocked.
When writing the module
Wrap your module in
"require('independence')(require, module, (function(require, module, exports) {" + yourCode + "}))"
.
// monkey.js require module { var moment = ; var _ = ; var myService = ; var myDatabase = ; exports { console; }; exports { console; };};
With CoffeeScript, you can require()
the provided
coffee-wrap to automatically wrap all your .coffee
modules
when transpiling them to JavaScript.
When using the module
This works as normal:
// someModule.js var monkey = ; monkey; // Will output `fling 2014-05-23`monkey; // Will output `swing 2`
When testing the module
// tests/monkey.js var monkey = ; { return { return "Yaaap!"; } ;} // Provide only moment and leave all other dependencies undefined:var pureMonkey = monkey; pureMonkey // Outputs `fling Yaaap!`pureMonkey // Fails because `_` is an empty Object // Override moment, but leave all other dependencies nominal:var testMonkey = monkey; testMonkey // Outputs `fling Yaaap!`testMonkey // Works as normal // Override moment in the monkey module and in ALL its wrapped dependencies// recursively (in this case, myService and myDatabase):var testMonkey = monkey;
But what if two modules have the same name?
// controller.jsvar userModel = ;var userController = ; ...
// tests/controller.jsvar controller = ; var testController = controller; ...
Other stuff you can do
Chain dependency objects:
var commonDependencies = lodash: myDatabase: {} { return 'serviced';}; var testMonkey = monkey
Clone & monkey-patch:
var database = ; var databaseTest = database;databaseTest { ;};
Coffee & Mocha
If you're using CoffeeScript and
Mocha you can use bin/coffee-wrap to
compiles and wraps .coffee
modules with the Independence header:
mocha --compilers coffee:independence/bin/coffee-wrap