Skip to content

Instantly share code, notes, and snippets.

@sommestad
Last active August 29, 2015 14:22
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 sommestad/6259f44b94bd43bebbf2 to your computer and use it in GitHub Desktop.
Save sommestad/6259f44b94bd43bebbf2 to your computer and use it in GitHub Desktop.
Experimental alternatives to Dependency Injection in Javascript
'use strict';
require('chai').should();
var sinon = require('sinon');
var cage = require('./monkey-cage.js');
describe(__filename, function() {
describe('openCage', function() {
beforeEach(function() {
sinon.stub(cage.deps.fs, 'writeFile').yieldsAsync();
});
afterEach(function() {
cage.deps.fs.restore();
});
it('should invoke fs.writeFile() with message', function(done) {
cage.openCage(function(err) {
var first_call = cage.deps.fs.writeFile.getCall(0),
expected_message = 'Unleashed 🐒 @ 23:27';
cage.deps.fs.writeFile.callCount.should.eql(1);
first_call.args[1].should.eql(expected_message);
done(err);
});
});
});
});
'use strict';
// Alternative with a create() function where deps are injected and bound to functions outside of closure (to make file easier to manage).
var externals = {};
exports.create = function(fs, path, error_factory) {
return {
openCage: externals.openCage.bind(null, fs)
};
};
externals.openCage = function(fs, callback) {
var caretakers_log_path = '/dev/null',
action = 'Unleashed 🐒 @ 23:27';
fs.writeFile(caretakers_log_path, action, callback);
};
if (process.env.NODE_ENV === 'test') {
exports.externals = externals;
}
'use strict';
// Alternative with a create() function where deps are injected
exports.create = function(fs, path, error_factory) {
return {
openCage: function(callback) {
var caretakers_log_path = '/dev/null',
action = 'Unleashed 🐒 @ 23:27';
fs.writeFile(caretakers_log_path, action, callback);
}
};
};
'use strict';
// Dependencies defined inside of exportable object for mocking during test,
// since it's a bit tedious to manage DI in Javascript. Ugly or Smart?
var deps = {
fs: require('fs'),
path: require('path'),
error_factory: require('error-factory')
};
exports.openCage = function(callback) {
var caretakers_log_path = '/dev/null',
action = 'Unleashed 🐒 @ 23:27';
deps.fs.writeFile(caretakers_log_path, action, callback);
};
if (process.env.NODE_ENV === 'test') {
exports.deps = deps;
}
@sommestad
Copy link
Author

Background story is that it doesn't feel fantastic to do regular dependency injection to modules (e.g. through a create() "construct").

Maybe this is a less obtrusive way of doing things? Or is it more messy to follow such a convention?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment