proxyquireify
Version:
Proxies browserify's require in order to allow overriding dependencies during testing.
94 lines (70 loc) • 2.89 kB
JavaScript
;
var fillMissingKeys = require('fill-keys');
var moduleNotFoundError = require('module-not-found-error');
function ProxyquireifyError(msg) {
this.name = 'ProxyquireifyError';
Error.captureStackTrace(this, ProxyquireifyError);
this.message = msg || 'An error occurred inside proxyquireify.';
}
function validateArguments(request, stubs) {
var msg = (function getMessage() {
if (!request)
return 'Missing argument: "request". Need it to resolve desired module.';
if (!stubs)
return 'Missing argument: "stubs". If no stubbing is needed, use regular require instead.';
if (typeof request != 'string')
return 'Invalid argument: "request". Needs to be a requirable string that is the module to load.';
if (typeof stubs != 'object')
return 'Invalid argument: "stubs". Needs to be an object containing overrides e.g., {"path": { extname: function () { ... } } }.';
})();
if (msg) throw new ProxyquireifyError(msg);
}
var stubs;
function stub(stubs_) {
stubs = stubs_;
// This cache is used by the prelude as an alternative to the regular cache.
// It is not read or written here, except to set it to an empty object when
// adding stubs and to reset it to null when clearing stubs.
module.exports._cache = {};
}
function reset() {
stubs = undefined;
module.exports._cache = null;
}
var proxyquire = module.exports = function (require_) {
if (typeof require_ != 'function')
throw new ProxyquireifyError(
'It seems like you didn\'t initialize proxyquireify with the require in your test.\n'
+ 'Make sure to correct this, i.e.: "var proxyquire = require(\'proxyquireify\')(require);"'
);
reset();
return function(request, stubs) {
validateArguments(request, stubs);
// set the stubs and require dependency
// when stub require is invoked by the module under test it will find the stubs here
stub(stubs);
var dep = require_(request);
reset();
return dep;
};
};
// Start with the default cache
proxyquire._cache = null;
proxyquire._proxy = function (require_, request) {
function original() {
return require_(request);
}
if (!stubs || !stubs.hasOwnProperty(request)) return original();
var stub = stubs[request];
if (stub === null) throw moduleNotFoundError(request)
var stubWideNoCallThru = Boolean(stubs['@noCallThru']) && (stub == null || stub['@noCallThru'] !== false);
var noCallThru = stubWideNoCallThru || (stub != null && Boolean(stub['@noCallThru']));
return noCallThru ? stub : fillMissingKeys(stub, original());
};
if (require.cache) {
// only used during build, so prevent browserify from including it
var replacePreludePath = './lib/replace-prelude';
var replacePrelude = require(replacePreludePath);
proxyquire.browserify = replacePrelude.browserify;
proxyquire.plugin = replacePrelude.plugin;
}