Skip to content

Instantly share code, notes, and snippets.

@arian
Last active December 13, 2015 19:58
Show Gist options
  • Save arian/4966457 to your computer and use it in GitHub Desktop.
Save arian/4966457 to your computer and use it in GitHub Desktop.
dependency injection example for mocking with testing
node_modules/
module.exports = require('./')._;
var _ = require('./')._ = require('./underscoreMocked');
require('./').http = require('./httpMocked');
var get = require('./get');
var expect = require('expect.js');
describe('get', function() {
it('should have called _.map', function(done) {
get("http://example.com", function(err, data) {
expect(data).to.eql([3, 6, 9]);
expect(_.map.callCount).to.be(1);
done();
});
});
});
var _ = require('./_');
var http = require('./http');
module.exports = function(url, callback) {
http.get(url, function(res) {
var data = '';
res.on('data', function(chunk) { data += chunk; });
res.on('end', function() {
data = JSON.parse(data);
// using the _ dependency here
callback(null, _.map(data, function(thing) {
return thing * 3;
}));
});
});
};
module.exports = require('./').http;
var EventEmitter = require('events').EventEmitter;
exports.get = function(options, callback){
var response = new EventEmitter();
callback(response);
response.emit('data', '[1,2,3]');
response.emit('end');
};
exports.http = require('http');
exports._ = require('underscore');
{
"name": "di",
"version": "0.0.0",
"description": "Dependency Injection Example",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://gist.github.com/4966457.git"
},
"author": "Arian Stolwijk",
"license": "MIT",
"dependencies": {
"mocha": "1.8",
"expect.js": "0.2",
"underscore": "1.4"
}
}
function map(array, callback, context){
map.callCount++;
return array.map(callback, context);
}
map.callCount = 0;
exports.map = map;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment