UNPKG

2.44 kBJavaScriptView Raw
1'use strict';
2
3function ProxyquireifyError(msg) {
4 this.name = 'ProxyquireifyError';
5 Error.captureStackTrace(this, ProxyquireifyError);
6 this.message = msg || 'An error occurred inside proxyquireify.';
7}
8
9function validateArguments(request, stubs) {
10 var msg = (function getMessage() {
11 if (!request)
12 return 'Missing argument: "request". Need it to resolve desired module.';
13
14 if (!stubs)
15 return 'Missing argument: "stubs". If no stubbing is needed, use regular require instead.';
16
17 if (typeof request != 'string')
18 return 'Invalid argument: "request". Needs to be a requirable string that is the module to load.';
19
20 if (typeof stubs != 'object')
21 return 'Invalid argument: "stubs". Needs to be an object containing overrides e.g., {"path": { extname: function () { ... } } }.';
22 })();
23
24 if (msg) throw new ProxyquireifyError(msg);
25}
26
27var stubs;
28
29function stub(stubs_) {
30 stubs = stubs_;
31}
32
33function reset() {
34 stubs = undefined;
35}
36
37function fillMissingKeys(mdl, original) {
38 Object.keys(original).forEach(function (key) {
39 if (!mdl[key]) mdl[key] = original[key];
40 });
41
42 return mdl;
43}
44
45var proxyquire = module.exports = function (require_) {
46 if (typeof require_ != 'function')
47 throw new ProxyquireifyError(
48 'It seems like you didn\'t initialize proxyquireify with the require in your test.\n'
49 + 'Make sure to correct this, i.e.: "var proxyquire = require(\'proxyquireify\')(require);"'
50 );
51
52 reset();
53
54 return function(request, stubs) {
55
56 validateArguments(request, stubs);
57
58 // set the stubs and require dependency
59 // when stub require is invoked by the module under test it will find the stubs here
60 stub(stubs);
61 var dep = require_(request);
62 reset();
63
64 return dep;
65 };
66};
67
68proxyquire.proxy = function (require_) {
69 return function (request) {
70 function original() {
71 return require_(request);
72 }
73
74 if (!stubs) return original();
75
76 var stub = stubs[request];
77
78 if (!stub) return original();
79
80 var stubWideNoCallThru = !!stubs['@noCallThru'] && stub['@noCallThru'] !== false;
81 var noCallThru = stubWideNoCallThru || !!stub['@noCallThru'];
82 return noCallThru ? stub : fillMissingKeys(stub, original());
83 };
84};
85
86if (require.cache) {
87 // only used during build, so prevent browserify from including it
88 var hackPrelude = './lib/hack-prelude';
89 proxyquire.browserify = require(hackPrelude).browserify;
90}