-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
HasteModuleLoader.js
670 lines (588 loc) · 22.1 KB
/
HasteModuleLoader.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/**
* Copyright (c) 2014, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/* eslint-disable fb-www/require-args, fb-www/object-create-only-one-param */
'use strict';
const fs = require('graceful-fs');
const moduleMocker = require('../lib/moduleMocker');
const HasteResolver = require('../resolvers/HasteResolver');
const path = require('path');
const resolve = require('resolve');
const transform = require('../lib/transform');
const NODE_PATH =
(process.env.NODE_PATH ? process.env.NODE_PATH.split(path.delimiter) : null);
const IS_PATH_BASED_MODULE_NAME = /^(?:\.\.?\/|\/)/;
const VENDOR_PATH = path.resolve(__dirname, '../../vendor');
const mockParentModule = {
id: 'mockParent',
exports: {},
};
const isFile = file => {
let stat;
try {
stat = fs.statSync(file);
} catch (err) {
if (err && err.code === 'ENOENT') {
return false;
}
}
return stat.isFile() || stat.isFIFO();
};
let _configUnmockListRegExpCache = null;
class Loader {
constructor(config, environment) {
this._config = config;
this._coverageCollectors = Object.create(null);
this._currentlyExecutingModulePath = '';
this._environment = environment;
this._explicitShouldMock = Object.create(null);
this._explicitlySetMocks = Object.create(null);
this._isCurrentlyExecutingManualMock = null;
this._mockMetaDataCache = Object.create(null);
this._shouldAutoMock = true;
this._configShouldMockModuleNames = Object.create(null);
this._extensions = config.moduleFileExtensions.map(ext => '.' + ext);
this._resolver = HasteResolver.get(
[config.rootDir],
{
extensions: this._extensions.concat(this._config.testFileExtensions),
ignoreFilePattern: [config.cacheDirectory]
.concat(config.modulePathIgnorePatterns).join('|'),
}
);
this._resolvedModules = Object.create(null);
this._resources = Object.create(null);
this._mocks = Object.create(null);
if (config.collectCoverage) {
this._CoverageCollector = require(config.coverageCollector);
}
if (_configUnmockListRegExpCache === null) {
_configUnmockListRegExpCache = new WeakMap();
}
if (
!config.unmockedModulePathPatterns ||
config.unmockedModulePathPatterns.length === 0
) {
this._unmockListRegExps = [];
} else {
this._unmockListRegExps = _configUnmockListRegExpCache.get(config);
if (!this._unmockListRegExps) {
this._unmockListRegExps = config.unmockedModulePathPatterns
.map(unmockPathRe => new RegExp(unmockPathRe));
_configUnmockListRegExpCache.set(config, this._unmockListRegExps);
}
}
// Workers communicate the config as JSON so we have to create a regex
// object in the module loader instance.
this._mappedModuleNames = Object.create(null);
if (this._config.moduleNameMapper.length) {
this._config.moduleNameMapper.forEach(
map => this._mappedModuleNames[map[1]] = new RegExp(map[0])
);
}
this.resetModuleRegistry();
}
resolveDependencies(path) {
return this._resolver.getDependencies(path)
.then(response => {
this._mocks = response.mocks;
this._resolvedModules = response.resolvedModules;
this._resources = response.resources;
})
.then(() => this);
}
requireModule(currPath, moduleName) {
const moduleID = this._getNormalizedModuleID(currPath, moduleName);
let modulePath;
// I don't like this behavior as it makes the module system's mocking
// rules harder to understand. Would much prefer that mock state were
// either "on" or "off" -- rather than "automock on", "automock off",
// "automock off -- but there's a manual mock, so you get that if you ask
// for the module and one doesnt exist", or "automock off -- but theres a
// useAutoMock: false entry in the package.json -- and theres a manual
// mock -- and the module is listed in the unMockList in the test config
// -- soooo...uhh...fuck I lost track".
//
// To simplify things I'd like to move to a system where tests must
// explicitly call .mock() on a module to receive the mocked version if
// automocking is off. If a manual mock exists, that is used. Otherwise
// we fall back to the automocking system to generate one for you.
//
// The only reason we're supporting this in jest for now is because we
// have some tests that depend on this behavior. I'd like to clean this
// up at some point in the future.
let manualMockResource = null;
let moduleResource = null;
moduleResource = this._getModule(moduleName);
manualMockResource = this._getMockModule(moduleName);
if (
!moduleResource &&
manualMockResource &&
manualMockResource.path !== this._isCurrentlyExecutingManualMock &&
this._explicitShouldMock[moduleID] !== false
) {
modulePath = manualMockResource.path;
}
if (resolve.isCore(moduleName)) {
return require(moduleName);
}
if (!modulePath) {
modulePath = this._resolveModuleName(currPath, moduleName);
}
// Always natively require the jasmine runner.
if (modulePath.indexOf(VENDOR_PATH) === 0) {
return require(modulePath);
}
if (!modulePath) {
throw new Error(`Cannot find module '${moduleName}' from '${currPath}'`);
}
let moduleObj;
moduleObj = this._moduleRegistry[modulePath];
if (!moduleObj) {
// We must register the pre-allocated module object first so that any
// circular dependencies that may arise while evaluating the module can
// be satisfied.
moduleObj = {
__filename: modulePath,
exports: {},
};
this._moduleRegistry[modulePath] = moduleObj;
if (path.extname(modulePath) === '.json') {
moduleObj.exports = this._environment.global.JSON.parse(
fs.readFileSync(modulePath, 'utf8')
);
} else if (path.extname(modulePath) === '.node') {
moduleObj.exports = require(modulePath);
} else {
this._execModule(moduleObj);
}
}
return moduleObj.exports;
}
requireMock(currPath, moduleName) {
const moduleID = this._getNormalizedModuleID(currPath, moduleName);
if (this._explicitlySetMocks[moduleID]) {
return this._explicitlySetMocks[moduleID];
}
let manualMockResource = this._getMockModule(moduleName);
let modulePath;
if (manualMockResource) {
modulePath = manualMockResource.path;
} else {
modulePath = this._resolveModuleName(currPath, moduleName);
// If the actual module file has a __mocks__ dir sitting immediately next
// to it, look to see if there is a manual mock for this file in that dir.
//
// The reason why node-haste isn't good enough for this is because
// node-haste only handles manual mocks for @providesModules well.
// Otherwise it's not good enough to disambiguate something like the
// following scenario:
//
// subDir1/MyModule.js
// subDir1/__mocks__/MyModule.js
// subDir2/MyModule.js
// subDir2/__mocks__/MyModule.js
//
// Where some other module does a relative require into each of the
// respective subDir{1,2} directories and expects a manual mock
// corresponding to that particular MyModule.js file.
const moduleDir = path.dirname(modulePath);
const moduleFileName = path.basename(modulePath);
const potentialManualMock =
path.join(moduleDir, '__mocks__', moduleFileName);
if (fs.existsSync(potentialManualMock)) {
manualMockResource = true;
modulePath = potentialManualMock;
}
}
if (this._mockRegistry[modulePath]) {
return this._mockRegistry[modulePath];
}
if (manualMockResource) {
const moduleObj = {
exports: {},
__filename: modulePath,
};
this._execModule(moduleObj);
this._mockRegistry[modulePath] = moduleObj.exports;
} else {
// Look for a real module to generate an automock from
this._mockRegistry[modulePath] = this._generateMock(
currPath,
moduleName
);
}
return this._mockRegistry[modulePath];
}
requireModuleOrMock(currPath, moduleName) {
if (this._shouldMock(currPath, moduleName)) {
return this.requireMock(currPath, moduleName);
} else {
return this.requireModule(currPath, moduleName);
}
}
resetModuleRegistry() {
this._mockRegistry = Object.create(null);
this._moduleRegistry = Object.create(null);
if (this._environment && this._environment.global) {
var envGlobal = this._environment.global;
Object.keys(envGlobal).forEach(key => {
const globalMock = envGlobal[key];
if (
(typeof globalMock === 'object' && globalMock !== null) ||
typeof globalMock === 'function'
) {
globalMock._isMockFunction && globalMock.mockClear();
}
});
if (envGlobal.mockClearTimers) {
envGlobal.mockClearTimers();
}
}
}
getAllTestPaths() {
return this._resolver.matchFilesByPattern(this._config.testDirectoryName);
}
getAllCoverageInfo() {
if (!this._config.collectCoverage) {
throw new Error(
'config.collectCoverage was not set, so no coverage info has been ' +
'(or will be) collected!'
);
}
const coverage = Object.create(null);
const collectors = this._coverageCollectors;
for (const filePath in collectors) {
coverage[filePath] = collectors[filePath].extractRuntimeCoverageInfo();
}
return coverage;
}
getCoverageForFilePath(filePath) {
if (!this._config.collectCoverage) {
throw new Error(
'config.collectCoverage was not set, so no coverage info has been ' +
'(or will be) collected!'
);
}
const collector = this._coverageCollectors[filePath];
return collector ? collector.extractRuntimeCoverageInfo() : null;
}
_execModule(moduleObj) {
// If the environment was disposed, prevent this module from
// being executed.
if (!this._environment.global) {
return;
}
const filename = moduleObj.__filename;
const collectors = this._coverageCollectors;
let moduleContent = transform(filename, this._config);
let collectorStore;
if (
this._config.collectCoverage &&
!filename.includes('/node_modules/')
) {
if (!collectors[filename]) {
collectors[filename] = new this._CoverageCollector(
moduleContent,
filename
);
}
const collector = collectors[filename];
collectorStore = collector.getCoverageDataStore();
moduleContent = collector.getInstrumentedSource('$JEST_COVERAGE_DATA');
}
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
// Every module receives a mock parent so they don't assume they are run
// standalone.
moduleObj.parent = mockParentModule;
moduleObj.require = this._createRequireImplementation(filename);
// Use this name for the module wrapper for consistency with node.
const evalResultVariable = 'Object.<anonymous>';
const wrapper = 'this["' + evalResultVariable + '"] = function(module, exports, require, __dirname, __filename, global, jest, $JEST_COVERAGE_DATA) {' + moduleContent + '\n};';
this._environment.runSourceText(wrapper, filename);
const wrapperFunc = this._environment.global[evalResultVariable];
delete this._environment.global[evalResultVariable];
wrapperFunc.call(
moduleObj.exports, // module context
moduleObj, // module object
moduleObj.exports, // module exports
moduleObj.require, // require implementation
path.dirname(filename), // __dirname
filename, // __filename
this._environment.global, // global object
this._createRuntimeFor(filename), // jest object
collectorStore // the coverage object
);
this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
this._currentlyExecutingModulePath = lastExecutingModulePath;
}
_generateMock(currPath, moduleName) {
const modulePath = this._resolveModuleName(currPath, moduleName);
if (!this._mockMetaDataCache[modulePath]) {
// This allows us to handle circular dependencies while generating an
// automock
this._mockMetaDataCache[modulePath] = moduleMocker.getMetadata({});
// In order to avoid it being possible for automocking to potentially
// cause side-effects within the module environment, we need to execute
// the module in isolation. This accomplishes that by temporarily
// clearing out the module and mock registries while the module being
// analyzed is executed.
//
// An example scenario where this could cause issue is if the module being
// mocked has calls into side-effectful APIs on another module.
const origMockRegistry = this._mockRegistry;
const origModuleRegistry = this._moduleRegistry;
this._mockRegistry = Object.create(null);
this._moduleRegistry = Object.create(null);
const moduleExports = this.requireModule(currPath, moduleName);
// Restore the "real" module/mock registries
this._mockRegistry = origMockRegistry;
this._moduleRegistry = origModuleRegistry;
const mockMetadata = moduleMocker.getMetadata(moduleExports);
if (mockMetadata === null) {
throw new Error('Failed to get mock metadata: ' + modulePath);
}
this._mockMetaDataCache[modulePath] = mockMetadata;
}
return moduleMocker.generateFromMetadata(
this._mockMetaDataCache[modulePath]
);
}
_resolveModuleName(currPath, moduleName) {
// Check if the resolver knows about this module
if (
this._resolvedModules[currPath] &&
this._resolvedModules[currPath][moduleName]
) {
return this._resolvedModules[currPath][moduleName].path;
} else {
// Otherwise it is likely a node_module.
return this._resolveNodeModule(currPath, moduleName);
}
}
_resolveNodeModule(currPath, moduleName) {
const basedir = path.dirname(currPath);
try {
return resolve.sync(moduleName, {
basedir,
extensions: this._extensions,
isFile,
paths: NODE_PATH,
readFileSync: fs.readFileSync,
});
} catch (e) {
// resolve.sync uses the basedir instead of currPath and therefore
// doesn't throw an accurate error message.
const relativePath = path.relative(basedir, currPath);
throw new Error(
`Cannot find module '${moduleName}' from '${relativePath || '.'}'`
);
}
}
_getModule(resourceName) {
return this._resources[resourceName];
}
_getMockModule(resourceName) {
if (this._mocks[resourceName]) {
return {
path: this._mocks[resourceName],
};
} else {
const moduleName = this._resolveStubModuleName(resourceName);
if (moduleName) {
return this._getModule(moduleName);
}
}
}
_getNormalizedModuleID(currPath, moduleName) {
let moduleType;
let mockAbsPath = null;
let realAbsPath = null;
if (resolve.isCore(moduleName)) {
moduleType = 'node';
realAbsPath = moduleName;
} else {
moduleType = 'user';
if (
IS_PATH_BASED_MODULE_NAME.test(moduleName) ||
(
this._getModule(moduleName) === undefined &&
this._getMockModule(moduleName) === undefined
)
) {
realAbsPath = this._resolveModuleName(currPath, moduleName);
if (realAbsPath == null) {
throw new Error(
`Cannot find module '${moduleName}' from '${currPath || '.'}'`
);
}
// Look up if this module has an associated manual mock.
const mockModule = this._getMockModule(moduleName);
if (mockModule) {
mockAbsPath = mockModule.path;
}
}
if (realAbsPath === null) {
const moduleResource = this._getModule(moduleName);
if (moduleResource) {
realAbsPath = moduleResource.path;
}
}
if (mockAbsPath === null) {
const mockResource = this._getMockModule(moduleName);
if (mockResource) {
mockAbsPath = mockResource.path;
}
}
}
const delimiter = path.delimiter;
return moduleType + delimiter + realAbsPath + delimiter + mockAbsPath;
}
_shouldMock(currPath, moduleName) {
const moduleID = this._getNormalizedModuleID(currPath, moduleName);
if (moduleID in this._explicitShouldMock) {
return this._explicitShouldMock[moduleID];
} else if (resolve.isCore(moduleName)) {
return false;
} else if (this._shouldAutoMock) {
// See if the module is specified in the config as a module that should
// never be mocked
if (this._configShouldMockModuleNames[moduleName]) {
return this._configShouldMockModuleNames[moduleName];
} else if (this._unmockListRegExps.length > 0) {
this._configShouldMockModuleNames[moduleName] = true;
const manualMockResource = this._getMockModule(moduleName);
let modulePath;
try {
modulePath = this._resolveModuleName(currPath, moduleName);
} catch (e) {
// If there isn't a real module, we don't have a path to match
// against the unmockList regexps. If there is also not a manual
// mock, then we throw because this module doesn't exist anywhere.
//
// However, it's possible that someone has a manual mock for a
// non-existent real module. In this case, we should mock the module
// (because we technically can).
//
// Ideally this should never happen, but we have some odd
// pre-existing edge-cases that rely on it so we need it for now.
//
// I'd like to eliminate this behavior in favor of requiring that
// all module environments are complete (meaning you can't just
// write a manual mock as a substitute for a real module).
if (manualMockResource) {
return true;
}
throw e;
}
let unmockRegExp;
// Never mock the jasmine environment.
if (modulePath.indexOf(VENDOR_PATH) === 0) {
return false;
}
const realPath = fs.realpathSync(modulePath);
this._configShouldMockModuleNames[moduleName] = true;
for (let i = 0; i < this._unmockListRegExps.length; i++) {
unmockRegExp = this._unmockListRegExps[i];
if (unmockRegExp.test(modulePath) ||
unmockRegExp.test(realPath)) {
return this._configShouldMockModuleNames[moduleName] = false;
}
}
return this._configShouldMockModuleNames[moduleName];
}
return true;
} else {
return false;
}
}
_resolveStubModuleName(moduleName) {
const nameMapper = this._mappedModuleNames;
for (const mappedModuleName in nameMapper) {
const regex = nameMapper[mappedModuleName];
if (regex.test(moduleName)) {
return mappedModuleName;
}
}
}
_createRequireImplementation(path) {
const moduleRequire = this.requireModuleOrMock.bind(this, path);
moduleRequire.requireMock = this.requireMock.bind(this, path);
moduleRequire.requireActual = this.requireModule.bind(this, path);
moduleRequire.resolve = moduleName => {
const ret = this._resolveModuleName(path, moduleName);
if (!ret) {
throw new Error(`Module(${moduleName}) not found!`);
}
return ret;
};
return moduleRequire;
}
_createRuntimeFor(currPath) {
const runtime = {
addMatchers: matchers => {
const jasmine = this._environment.global.jasmine;
jasmine.getEnv().currentSpec.addMatchers(matchers);
},
autoMockOff: () => {
this._shouldAutoMock = false;
return runtime;
},
autoMockOn: () => {
this._shouldAutoMock = true;
return runtime;
},
clearAllTimers: () => this._environment.fakeTimers.clearAllTimers(),
currentTestPath: () => this._environment.testFilePath,
dontMock: moduleName => {
const moduleID = this._getNormalizedModuleID(currPath, moduleName);
this._explicitShouldMock[moduleID] = false;
return runtime;
},
getTestEnvData: () => {
const frozenCopy = {};
// Make a shallow copy only because a deep copy seems like
// overkill..
Object.keys(this._config.testEnvData).forEach(
key => frozenCopy[key] = this._config.testEnvData[key]
);
Object.freeze(frozenCopy);
return frozenCopy;
},
genMockFromModule: moduleName => this._generateMock(currPath, moduleName),
genMockFunction: moduleMocker.getMockFunction,
genMockFn: moduleMocker.getMockFunction,
mock: moduleName => {
const moduleID = this._getNormalizedModuleID(currPath, moduleName);
this._explicitShouldMock[moduleID] = true;
return runtime;
},
resetModuleRegistry: () => {
this.resetModuleRegistry();
return runtime;
},
runAllTicks: () => this._environment.fakeTimers.runAllTicks(),
runAllImmediates: () => this._environment.fakeTimers.runAllImmediates(),
runAllTimers: () => this._environment.fakeTimers.runAllTimers(),
runOnlyPendingTimers: () =>
this._environment.fakeTimers.runOnlyPendingTimers(),
setMock: (moduleName, moduleExports) => {
const moduleID = this._getNormalizedModuleID(currPath, moduleName);
this._explicitShouldMock[moduleID] = true;
this._explicitlySetMocks[moduleID] = moduleExports;
return runtime;
},
useFakeTimers: () => this._environment.fakeTimers.useFakeTimers(),
useRealTimers: () => this._environment.fakeTimers.useRealTimers(),
};
return runtime;
}
}
module.exports = Loader;