Skip to content

Instantly share code, notes, and snippets.

@mattiaerre
Last active September 6, 2015 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattiaerre/b9314145f8dd4b071114 to your computer and use it in GitHub Desktop.
Save mattiaerre/b9314145f8dd4b071114 to your computer and use it in GitHub Desktop.
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