This repository has been archived by the owner on Apr 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
mockery.js
366 lines (327 loc) · 11.6 KB
/
mockery.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
Copyrights for code authored by Yahoo! Inc. is licensed under the following
terms:
MIT License
Copyright (c) 2011-2012 Yahoo! Inc. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/*
* A library that enables the hooking of the standard 'require' function, such
* that a (possibly partial) mock implementation can be provided instead. This
* is most useful for running unit tests, since any dependency obtained through
* 'require' can be mocked out.
*/
"use strict";
var m = require('module'),
registeredMocks = {},
registeredSubstitutes = {},
registeredAllowables = {},
originalLoader = null,
originalCache = null,
defaultOptions = {
useCleanCache: false,
warnOnReplace: true,
warnOnUnregistered: true
},
options = {};
/*
* Merge the supplied options in with a new copy of the default options to get
* the effective options, and return those.
*/
function getEffectiveOptions(opts) {
var options = {};
Object.keys(defaultOptions).forEach(function (key) {
options[key] = defaultOptions[key];
});
if (opts) {
Object.keys(opts).forEach(function (key) {
options[key] = opts[key];
});
}
return options;
}
/*
* The (private) loader replacement that is used when hooking is enabled. It
* does the work of returning a mock or substitute when configured, reporting
* non-allowed modules, and invoking the original loader when appropriate.
* The signature of this function *must* match that of Node's Module._load,
* since it will replace that when mockery is enabled.
*/
function hookedLoader(request, parent, isMain) {
var subst, allow, file;
if (!originalLoader) {
throw new Error("Loader has not been hooked");
}
if (registeredMocks.hasOwnProperty(request)) {
return registeredMocks[request];
}
if (registeredSubstitutes.hasOwnProperty(request)) {
subst = registeredSubstitutes[request];
if (!subst.module && subst.name) {
subst.module = originalLoader(subst.name, parent, isMain);
}
if (!subst.module) {
throw new Error("Misconfigured substitute for '" + request + "'");
}
return subst.module;
}
if (registeredAllowables.hasOwnProperty(request)) {
allow = registeredAllowables[request];
if (allow.unhook) {
file = m._resolveFilename(request, parent);
if ((file.indexOf('/') !== -1 || file.indexOf('\\') !== -1) && allow.paths.indexOf(file) === -1) {
allow.paths.push(file);
}
}
} else {
if (options.warnOnUnregistered) {
console.warn("WARNING: loading non-allowed module: " + request);
}
}
return originalLoader(request, parent, isMain);
}
/*
* Enables mockery by hooking subsequent 'require' invocations. Note that *all*
* 'require' invocations will be hooked until 'disable' is called. Calling this
* function more than once will have no ill effects.
*/
function enable(opts) {
if (originalLoader) {
// Already hooked
return;
}
options = getEffectiveOptions(opts);
if (options.useCleanCache) {
originalCache = m._cache;
m._cache = {};
repopulateNative();
}
originalLoader = m._load;
m._load = hookedLoader;
}
/*
* Disables mockery by unhooking from the Node loader. No subsequent 'require'
* invocations will be seen by mockery. Calling this function more than once
* will have no ill effects.
*/
function disable() {
if (!originalLoader) {
// Not hooked
return;
}
if (options.useCleanCache) {
// Previously this just set m._cache to originalCache. This would make
// node re-require native addons that were required while mockery was
// enabled, which breaks it in node@>=0.12. Instead populate
// originalCache with any native addons that were first required since
// mockery was enabled.
Object.keys(m._cache).forEach(function(k){
if (k.indexOf('\.node') > -1 && !originalCache[k]) {
originalCache[k] = m._cache[k];
}
});
removeParentReferences();
m._cache = originalCache;
originalCache = null;
}
m._load = originalLoader;
originalLoader = null;
}
/*
* If the clean cache option is in effect, reset the module cache to an empty
* state. Calling this function when the clean cache option is not in effect
* will have no ill effects, but will do nothing.
*/
function resetCache() {
if (options.useCleanCache && originalCache) {
removeParentReferences();
m._cache = {};
repopulateNative();
}
}
/*
* Starting in node 0.12 node won't reload native modules
* The reason is that native modules can register themselves to be loaded automatically
* This will re-populate the cache with the native modules that have not been mocked
*/
function repopulateNative() {
Object.keys(originalCache).forEach(function(k) {
if (k.indexOf('\.node') > -1 && !m._cache[k]) {
m._cache[k] = originalCache[k];
}
});
}
/*
* Enable or disable warnings to the console when previously registered mocks
* and subsitutes are replaced.
*/
function warnOnReplace(enable) {
options.warnOnReplace = enable;
}
/*
* Enable or disable warnings to the console when modules are loaded that have
* not been registered as a mock, a substitute, or allowed.
*/
function warnOnUnregistered(enable) {
options.warnOnUnregistered = enable;
}
/*
* Register a mock object for the specified module. While mockery is enabled,
* any subsequent 'require' for this module will return the mock object. The
* mock need not mock out all original exports, but no fallback is provided
* for anything not mocked and subsequently invoked.
*/
function registerMock(mod, mock) {
if (options.warnOnReplace && registeredMocks.hasOwnProperty(mod)) {
console.warn("WARNING: Replacing existing mock for module: " + mod);
}
registeredMocks[mod] = mock;
}
/*
* Deregister a mock object for the specified module. A subsequent 'require' for
* that module will revert to the previous behaviour (which, by default, means
* falling back to the original 'require' behaviour).
*/
function deregisterMock(mod) {
if (registeredMocks.hasOwnProperty(mod)) {
delete registeredMocks[mod];
}
}
/*
* Register a substitute module for the specified module. While mockery is
* enabled, any subsequent 'require' for this module will be effectively
* replaced by a 'require' for the substitute module. This is useful when
* a mock implementation is itself implemented as a module.
*/
function registerSubstitute(mod, subst) {
if (options.warnOnReplace && registeredSubstitutes.hasOwnProperty(mod)) {
console.warn("WARNING: Replacing existing substitute for module: " + mod);
}
registeredSubstitutes[mod] = {
name: subst
};
}
/*
* Deregister a substitute module for the specified module. A subsequent
* 'require' for that module will revert to the previous behaviour (which, by
* default, means falling back to the original 'require' behaviour).
*/
function deregisterSubstitute(mod) {
if (registeredSubstitutes.hasOwnProperty(mod)) {
delete registeredSubstitutes[mod];
}
}
/*
* Register a module as 'allowed', meaning that, even if a mock or substitute
* for it has not been registered, mockery will not complain when it is loaded
* via 'require'. This encourages the user to consciously declare the modules
* that will be loaded and used in the original form, thus avoiding warnings.
*
* If 'unhook' is true, the module will be removed from the module cache when
* it is deregistered.
*/
function registerAllowable(mod, unhook) {
registeredAllowables[mod] = {
unhook: !!unhook,
paths: []
};
}
/*
* Register an array of modules as 'allowed'. This is a convenience function
* that performs the same function as 'registerAllowable' but for an array of
* modules rather than a single module.
*/
function registerAllowables(mods, unhook) {
mods.forEach(function (mod) {
registerAllowable(mod, unhook);
});
}
/*
* Deregister a module as 'allowed'. A subsequent 'require' for that module
* will generate a warning that the module is not allowed, unless or until a
* mock or substitute is registered for that module.
*/
function deregisterAllowable(mod) {
if (registeredAllowables.hasOwnProperty(mod)) {
var allow = registeredAllowables[mod];
if (allow.unhook) {
allow.paths.forEach(function (p) {
delete m._cache[p];
});
}
delete registeredAllowables[mod];
}
}
/*
* Deregister an array of modules as 'allowed'. This is a convenience function
* that performs the same function as 'deregisterAllowable' but for an array of
* modules rather than a single module.
*/
function deregisterAllowables(mods) {
mods.forEach(function (mod) {
deregisterAllowable(mod);
});
}
/*
* Deregister all mocks, substitutes, and allowed modules, resetting the state
* to a clean slate. This does not affect the enabled / disabled state of
* mockery, though.
*/
function deregisterAll() {
Object.keys(registeredAllowables).forEach(function (mod) {
var allow = registeredAllowables[mod];
if (allow.unhook) {
allow.paths.forEach(function (p) {
delete m._cache[p];
});
}
});
registeredMocks = {};
registeredSubstitutes = {};
registeredAllowables = {};
}
/**
* Remove references to modules in the mockery cache from
* their parents' children.
*/
function removeParentReferences() {
Object.keys(m._cache).forEach(function(k){
if (k.indexOf('\.node') === -1) {
// don't touch native modules, because they're special
var mod = m._cache[k];
var idx = mod.parent && mod.parent.children && mod.parent.children.indexOf(mod);
if (idx > -1) {
mod.parent.children.splice(idx, 1);
}
}
});
}
// Exported functions
exports.enable = enable;
exports.disable = disable;
exports.resetCache = resetCache;
exports.warnOnReplace = warnOnReplace;
exports.warnOnUnregistered = warnOnUnregistered;
exports.registerMock = registerMock;
exports.registerSubstitute = registerSubstitute;
exports.registerAllowable = registerAllowable;
exports.registerAllowables = registerAllowables;
exports.deregisterMock = deregisterMock;
exports.deregisterSubstitute = deregisterSubstitute;
exports.deregisterAllowable = deregisterAllowable;
exports.deregisterAllowables = deregisterAllowables;
exports.deregisterAll = deregisterAll;