There are many ways to add features in Unit.js.
- Monkey patching like
test.myFeature = myFeature
- Dependency injection
- Plugin
Unit.js provides a plugins system easy to use (based on Noder.io) for extending Unit.js's assertions and interfaces.
It is possible to create a package works easily as a plugin for Unit.js and also as a standalone module or library.
The creation of a plugin Unit.js can be useful to re-use code across multiple projects.
Also, for a large application with its specific modules, it may be useful to create a special plugin to facilitate the tests of each module (module initialization, handle the database via the ORM used by the application, test the controllers, ...).
If you publish a plugin for Unit.js, please let me know. I'll add it in the documentation :)
Example
File: plugins/test-blog.js.
/**
* Initialization for use as a standalone module.
* @return {UnitJS} New `UnitJS` instance
*/
module.exports = function blog() {
return module.exports.__noder(require('unit.js'));
};
/**
* Init `blog` plugin.
* @param {UnitJS|Noder} test Unit.js (or Noder) instance.
* @return {UnitJS|Noder} Current Unit.js (or Noder) instance.
*/
module.exports.__noder = function blogPlugin(test) {
// update the config object
test.$di.merge({
config: {
env : 'test',
domain : 'localhost'
}
});
// sub-modules that provide generic tests for the blog
test.use(require('./api/article'));
test.use(require('./api/comment'));
test.use(require('./api/admin'));
return test;
};
File: some-file.js.
Use as a plugin:
var test = require('unit.js');
test.use('./plugins/test-blog');
Use as a standalone module:
var test = require('./plugins/test-blog');