Last active
December 20, 2015 17:59
-
-
Save sunwukung/6172433 to your computer and use it in GitHub Desktop.
wraps require to enable the injection of mocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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