Skip to content

Instantly share code, notes, and snippets.

@sunwukung
Last active December 20, 2015 17:59
Show Gist options
  • Save sunwukung/6172433 to your computer and use it in GitHub Desktop.
Save sunwukung/6172433 to your computer and use it in GitHub Desktop.
wraps require to enable the injection of mocks
/*
module loader
primary purpose is to provide a way of
injecting mocks into nodeJS modules
secondary purpose is to eliminate relative
paths in require statements
*/
var l = {},
_ = require('lodash'),
path = require('path');
l.specs = {};
l.origin = '';
l.init = function (origin, specs) {
// init(string/origin, object/options)
// origin: provides root folder of project
// specs: provides mock objects/path mapping
l.origin = origin;
if (specs) {
l.specs = specs;
}
};
l.load = function (id) {
// load(string/id)
// tries to locate id in mocks object
if (l.specs.hasOwnProperty(id)) {
if (_.isObject(l.specs[id])) {
return l.specs[id];
}
if (_.isString(l.specs[id])) {
return require(l.origin + l.specs[id]);
}
// misconfigured
console.log('non string/object located in l.specs');
} else {
if(id !== 'apiService') {
return require(id);
}
}
};
l.reset = function () {
l.specs = {};
l.origin = '';
};
module.exports = l;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment