Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dependency injection in Node.js
var chai = require('chai'),
expect = chai.expect,
should = chai.should();
describe('unit-tests', function () {
'use strict'
describe('generic-component-tests', function () {
describe('given a component', function () {
describe('when initialized w/ dependency', function () {
it('then it should use the dependency injected', function (done) {
var dependency = { doSomething: function (name) { return 'hello ' + name; } };
var component = require('../../src/generic-component')(dependency);
var message = component.getMessage('mattia');
expect(message).to.be.equal('hello mattia');
done();
});
});
describe('when initialized w/out dependency', function () {
it('then it should use the dependency declared internally', function (done) {
var component = require('../../src/generic-component')();
var message = component.getMessage('mattia');
expect(message).to.be.equal('ciao mattia');
done();
});
});
});
});
});
function genericComponent(dependency) {
'use strict';
dependency = dependency || { doSomething: function (name) { return 'ciao ' + name } };
function getMessage(name) {
return dependency.doSomething(name);
}
return {
getMessage: getMessage,
}
}
module.exports = genericComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment