Created
November 13, 2014 19:30
-
-
Save ecasilla/49920ffdc9bf3fa83dae to your computer and use it in GitHub Desktop.
Node Mock Module Loader
This file contains hidden or 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
var vm = require('vm'); | |
var fs = require('fs'); | |
var path = require('path'); | |
/** | |
* Helper for unit testing: | |
* - load module with mocked dependencies | |
* - allow accessing private state of the module | |
* | |
* @param {string} filePath Absolute path to module (file to load) | |
* @param {Object=} mocks Hash of mocked dependencies | |
*/ | |
exports.loadModule = function(filePath, mocks) { | |
mocks = mocks || {}; | |
// this is necessary to allow relative path modules within loaded file | |
// i.e. requiring ./some inside file /a/b.js needs to be resolved to /a/some | |
var resolveModule = function(module) { | |
if (module.charAt(0) !== '.') return module; | |
return path.resolve(path.dirname(filePath), module); | |
}; | |
var exports = {}; | |
var context = { | |
require: function(name) { | |
return mocks[name] || require(resolveModule(name)); | |
}, | |
console: console, | |
exports: exports, | |
module: { | |
exports: exports | |
} | |
}; | |
vm.runInNewContext(fs.readFileSync(filePath), context); | |
return context; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment