-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
index.ts
1045 lines (940 loc) · 32.2 KB
/
index.ts
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path';
import {Config, SourceMaps} from '@jest/types';
import {
Jest,
JestEnvironment,
LocalModuleRequire,
Module,
} from '@jest/environment';
import jestMock, {MockFunctionMetadata} from 'jest-mock';
import HasteMap, {ModuleMap} from 'jest-haste-map';
import {formatStackTrace, separateMessageFromStack} from 'jest-message-util';
import Resolver from 'jest-resolve';
import {createDirectory, deepCyclicCopy} from 'jest-util';
import {escapePathForRegex} from 'jest-regex-util';
import Snapshot from 'jest-snapshot';
import {
ScriptTransformer,
ShouldInstrumentOptions,
shouldInstrument,
} from '@jest/transform';
import fs from 'graceful-fs';
import stripBOM from 'strip-bom';
import {run as cliRun} from './cli';
import {options as cliOptions} from './cli/args';
import {findSiblingsWithFileExtension} from './helpers';
import {Context} from './types';
type HasteMapOptions = {
console?: Console;
maxWorkers: number;
resetCache: boolean;
watch?: boolean;
watchman: boolean;
};
type InternalModuleOptions = {
isInternalModule: boolean;
};
type InitialModule = Partial<Module> &
Pick<Module, 'children' | 'exports' | 'filename' | 'id' | 'loaded'>;
type ModuleRegistry = {[key: string]: InitialModule | Module};
type ResolveOptions = Parameters<typeof require.resolve>[1];
type BooleanObject = {[key: string]: boolean};
type CacheFS = {[path: string]: string};
const testTimeoutSymbol = Symbol.for('TEST_TIMEOUT_SYMBOL');
const retryTimesSymbol = Symbol.for('RETRY_TIMES');
const NODE_MODULES = path.sep + 'node_modules' + path.sep;
const getModuleNameMapper = (config: Config.ProjectConfig) => {
if (
Array.isArray(config.moduleNameMapper) &&
config.moduleNameMapper.length
) {
return config.moduleNameMapper.map(([regex, moduleName]) => ({
moduleName,
regex: new RegExp(regex),
}));
}
return null;
};
const unmockRegExpCache = new WeakMap();
class Runtime {
static ScriptTransformer: typeof ScriptTransformer;
private _cacheFS: CacheFS;
private _config: Config.ProjectConfig;
private _coverageOptions: ShouldInstrumentOptions;
private _currentlyExecutingModulePath: string;
private _environment: JestEnvironment;
private _explicitShouldMock: BooleanObject;
private _internalModuleRegistry: ModuleRegistry;
private _isCurrentlyExecutingManualMock: string | null;
private _mockFactories: {[key: string]: () => unknown};
private _mockMetaDataCache: {
[key: string]: MockFunctionMetadata<unknown, unknown[]>;
};
private _mockRegistry: {[key: string]: any};
private _isolatedMockRegistry: {[key: string]: any} | null;
private _moduleMocker: typeof jestMock;
private _isolatedModuleRegistry: ModuleRegistry | null;
private _moduleRegistry: ModuleRegistry;
private _needsCoverageMapped: Set<string>;
private _resolver: Resolver;
private _shouldAutoMock: boolean;
private _shouldMockModuleCache: BooleanObject;
private _shouldUnmockTransitiveDependenciesCache: BooleanObject;
private _sourceMapRegistry: SourceMaps.SourceMapRegistry;
private _scriptTransformer: ScriptTransformer;
private _transitiveShouldMock: BooleanObject;
private _unmockList: RegExp | undefined;
private _virtualMocks: BooleanObject;
constructor(
config: Config.ProjectConfig,
environment: JestEnvironment,
resolver: Resolver,
cacheFS?: CacheFS,
coverageOptions?: ShouldInstrumentOptions,
) {
this._cacheFS = cacheFS || Object.create(null);
this._config = config;
this._coverageOptions = coverageOptions || {
changedFiles: undefined,
collectCoverage: false,
collectCoverageFrom: [],
collectCoverageOnlyFrom: null,
};
this._currentlyExecutingModulePath = '';
this._environment = environment;
this._explicitShouldMock = Object.create(null);
this._internalModuleRegistry = Object.create(null);
this._isCurrentlyExecutingManualMock = null;
this._mockFactories = Object.create(null);
this._mockRegistry = Object.create(null);
this._moduleMocker = this._environment.moduleMocker;
this._isolatedModuleRegistry = null;
this._isolatedMockRegistry = null;
this._moduleRegistry = Object.create(null);
this._needsCoverageMapped = new Set();
this._resolver = resolver;
this._scriptTransformer = new ScriptTransformer(config);
this._shouldAutoMock = config.automock;
this._sourceMapRegistry = Object.create(null);
this._virtualMocks = Object.create(null);
this._mockMetaDataCache = Object.create(null);
this._shouldMockModuleCache = Object.create(null);
this._shouldUnmockTransitiveDependenciesCache = Object.create(null);
this._transitiveShouldMock = Object.create(null);
this._unmockList = unmockRegExpCache.get(config);
if (!this._unmockList && config.unmockedModulePathPatterns) {
this._unmockList = new RegExp(
config.unmockedModulePathPatterns.join('|'),
);
unmockRegExpCache.set(config, this._unmockList);
}
if (config.automock) {
config.setupFiles.forEach(filePath => {
if (filePath && filePath.includes(NODE_MODULES)) {
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
filePath,
);
this._transitiveShouldMock[moduleID] = false;
}
});
}
this.resetModules();
if (config.setupFiles.length) {
for (let i = 0; i < config.setupFiles.length; i++) {
this.requireModule(config.setupFiles[i]);
}
}
}
// TODO: Can this be `static shouldInstrument = shouldInstrument;`?
static shouldInstrument(
filename: Config.Path,
options: ShouldInstrumentOptions,
config: Config.ProjectConfig,
) {
return shouldInstrument(filename, options, config);
}
static createContext(
config: Config.ProjectConfig,
options: {
console?: Console;
maxWorkers: number;
watch?: boolean;
watchman: boolean;
},
): Promise<Context> {
createDirectory(config.cacheDirectory);
const instance = Runtime.createHasteMap(config, {
console: options.console,
maxWorkers: options.maxWorkers,
resetCache: !config.cache,
watch: options.watch,
watchman: options.watchman,
});
return instance.build().then(
hasteMap => ({
config,
hasteFS: hasteMap.hasteFS,
moduleMap: hasteMap.moduleMap,
resolver: Runtime.createResolver(config, hasteMap.moduleMap),
}),
error => {
throw error;
},
);
}
static createHasteMap(
config: Config.ProjectConfig,
options?: HasteMapOptions,
): HasteMap {
const ignorePatternParts = [
...config.modulePathIgnorePatterns,
...(options && options.watch ? config.watchPathIgnorePatterns : []),
config.cacheDirectory.startsWith(config.rootDir + path.sep) &&
config.cacheDirectory,
].filter(Boolean);
const ignorePattern =
ignorePatternParts.length > 0
? new RegExp(ignorePatternParts.join('|'))
: undefined;
return new HasteMap({
cacheDirectory: config.cacheDirectory,
computeSha1: config.haste.computeSha1,
console: options && options.console,
dependencyExtractor: config.dependencyExtractor,
extensions: [Snapshot.EXTENSION].concat(config.moduleFileExtensions),
hasteImplModulePath: config.haste.hasteImplModulePath,
ignorePattern,
maxWorkers: (options && options.maxWorkers) || 1,
mocksPattern: escapePathForRegex(path.sep + '__mocks__' + path.sep),
name: config.name,
platforms: config.haste.platforms || ['ios', 'android'],
providesModuleNodeModules: config.haste.providesModuleNodeModules,
resetCache: options && options.resetCache,
retainAllFiles: false,
rootDir: config.rootDir,
roots: config.roots,
useWatchman: options && options.watchman,
watch: options && options.watch,
});
}
static createResolver(
config: Config.ProjectConfig,
moduleMap: ModuleMap,
): Resolver {
return new Resolver(moduleMap, {
browser: config.browser,
defaultPlatform: config.haste.defaultPlatform,
extensions: config.moduleFileExtensions.map(extension => '.' + extension),
hasCoreModules: true,
moduleDirectories: config.moduleDirectories,
moduleNameMapper: getModuleNameMapper(config),
modulePaths: config.modulePaths,
platforms: config.haste.platforms,
resolver: config.resolver,
rootDir: config.rootDir,
});
}
static runCLI(args?: Config.Argv, info?: Array<string>) {
return cliRun(args, info);
}
static getCLIOptions() {
return cliOptions;
}
requireModule(
from: Config.Path,
moduleName?: string,
options?: InternalModuleOptions,
isRequireActual?: boolean | null,
) {
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
);
let modulePath;
// Some old tests rely on this mocking behavior. Ideally we'll change this
// to be more explicit.
const moduleResource = moduleName && this._resolver.getModule(moduleName);
const manualMock =
moduleName && this._resolver.getMockModule(from, moduleName);
if (
(!options || !options.isInternalModule) &&
!isRequireActual &&
!moduleResource &&
manualMock &&
manualMock !== this._isCurrentlyExecutingManualMock &&
this._explicitShouldMock[moduleID] !== false
) {
modulePath = manualMock;
}
if (moduleName && this._resolver.isCoreModule(moduleName)) {
return this._requireCoreModule(moduleName);
}
if (!modulePath) {
modulePath = this._resolveModule(from, moduleName);
}
let moduleRegistry;
if (!options || !options.isInternalModule) {
if (this._moduleRegistry[modulePath] || !this._isolatedModuleRegistry) {
moduleRegistry = this._moduleRegistry;
} else {
moduleRegistry = this._isolatedModuleRegistry;
}
} else {
moduleRegistry = this._internalModuleRegistry;
}
if (!moduleRegistry[modulePath]) {
// We must register the pre-allocated module object first so that any
// circular dependencies that may arise while evaluating the module can
// be satisfied.
const localModule: InitialModule = {
children: [],
exports: {},
filename: modulePath,
id: modulePath,
loaded: false,
};
moduleRegistry[modulePath] = localModule;
if (path.extname(modulePath) === '.json') {
localModule.exports = this._environment.global.JSON.parse(
stripBOM(fs.readFileSync(modulePath, 'utf8')),
);
} else if (path.extname(modulePath) === '.node') {
localModule.exports = require(modulePath);
} else {
// Only include the fromPath if a moduleName is given. Else treat as root.
const fromPath = moduleName ? from : null;
this._execModule(localModule, options, moduleRegistry, fromPath);
}
localModule.loaded = true;
}
return moduleRegistry[modulePath].exports;
}
requireInternalModule(from: Config.Path, to?: string) {
return this.requireModule(from, to, {isInternalModule: true});
}
requireActual(from: Config.Path, moduleName: string) {
return this.requireModule(from, moduleName, undefined, true);
}
requireMock(from: Config.Path, moduleName: string) {
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
);
if (this._isolatedMockRegistry && this._isolatedMockRegistry[moduleID]) {
return this._isolatedMockRegistry[moduleID];
} else if (this._mockRegistry[moduleID]) {
return this._mockRegistry[moduleID];
}
const mockRegistry = this._isolatedMockRegistry || this._mockRegistry;
if (moduleID in this._mockFactories) {
return (mockRegistry[moduleID] = this._mockFactories[moduleID]());
}
const manualMockOrStub = this._resolver.getMockModule(from, moduleName);
let modulePath;
if (manualMockOrStub) {
modulePath = this._resolveModule(from, manualMockOrStub);
} else {
modulePath = this._resolveModule(from, moduleName);
}
let isManualMock =
manualMockOrStub &&
!this._resolver.resolveStubModuleName(from, moduleName);
if (!isManualMock) {
// 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.
//
// subDir1/my_module.js
// subDir1/__mocks__/my_module.js
// subDir2/my_module.js
// subDir2/__mocks__/my_module.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 my_module.js file.
const moduleDir = path.dirname(modulePath);
const moduleFileName = path.basename(modulePath);
const potentialManualMock = path.join(
moduleDir,
'__mocks__',
moduleFileName,
);
if (fs.existsSync(potentialManualMock)) {
isManualMock = true;
modulePath = potentialManualMock;
}
}
if (isManualMock) {
const localModule: InitialModule = {
children: [],
exports: {},
filename: modulePath,
id: modulePath,
loaded: false,
};
// Only include the fromPath if a moduleName is given. Else treat as root.
const fromPath = moduleName ? from : null;
this._execModule(localModule, undefined, mockRegistry, fromPath);
mockRegistry[moduleID] = localModule.exports;
localModule.loaded = true;
} else {
// Look for a real module to generate an automock from
mockRegistry[moduleID] = this._generateMock(from, moduleName);
}
return mockRegistry[moduleID];
}
requireModuleOrMock(from: Config.Path, moduleName: string) {
try {
if (this._shouldMock(from, moduleName)) {
return this.requireMock(from, moduleName);
} else {
return this.requireModule(from, moduleName);
}
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
const appendedMessage = findSiblingsWithFileExtension(
this._config.moduleFileExtensions,
from,
moduleName,
);
if (appendedMessage) {
e.message += appendedMessage;
}
}
throw e;
}
}
isolateModules(fn: () => void) {
if (this._isolatedModuleRegistry || this._isolatedMockRegistry) {
throw new Error(
'isolateModules cannot be nested inside another isolateModules.',
);
}
this._isolatedModuleRegistry = Object.create(null);
this._isolatedMockRegistry = Object.create(null);
fn();
this._isolatedModuleRegistry = null;
this._isolatedMockRegistry = null;
}
resetModules() {
this._isolatedModuleRegistry = null;
this._isolatedMockRegistry = null;
this._mockRegistry = Object.create(null);
this._moduleRegistry = Object.create(null);
if (this._environment) {
if (this._environment.global) {
const envGlobal = this._environment.global;
(Object.keys(envGlobal) as Array<keyof NodeJS.Global>).forEach(key => {
const globalMock = envGlobal[key];
if (
((typeof globalMock === 'object' && globalMock !== null) ||
typeof globalMock === 'function') &&
globalMock._isMockFunction === true
) {
globalMock.mockClear();
}
});
}
if (this._environment.fakeTimers) {
this._environment.fakeTimers.clearAllTimers();
}
}
}
getAllCoverageInfoCopy() {
return deepCyclicCopy(this._environment.global.__coverage__);
}
getSourceMapInfo(coveredFiles: Set<string>) {
return Object.keys(this._sourceMapRegistry).reduce<{
[path: string]: string;
}>((result, sourcePath) => {
if (
coveredFiles.has(sourcePath) &&
this._needsCoverageMapped.has(sourcePath) &&
fs.existsSync(this._sourceMapRegistry[sourcePath])
) {
result[sourcePath] = this._sourceMapRegistry[sourcePath];
}
return result;
}, {});
}
getSourceMaps(): SourceMaps.SourceMapRegistry {
return this._sourceMapRegistry;
}
setMock(
from: string,
moduleName: string,
mockFactory: () => unknown,
options?: {virtual?: boolean},
) {
if (options && options.virtual) {
const mockPath = this._resolver.getModulePath(from, moduleName);
this._virtualMocks[mockPath] = true;
}
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
);
this._explicitShouldMock[moduleID] = true;
this._mockFactories[moduleID] = mockFactory;
}
restoreAllMocks() {
this._moduleMocker.restoreAllMocks();
}
resetAllMocks() {
this._moduleMocker.resetAllMocks();
}
clearAllMocks() {
this._moduleMocker.clearAllMocks();
}
private _resolveModule(from: Config.Path, to?: string) {
return to ? this._resolver.resolveModule(from, to) : from;
}
private _requireResolve(
from: Config.Path,
moduleName?: string,
options: ResolveOptions = {},
) {
if (moduleName == null) {
throw new Error(
'The first argument to require.resolve must be a string. Received null or undefined.',
);
}
const {paths} = options;
if (paths) {
for (const p of paths) {
const absolutePath = path.resolve(from, '..', p);
const module = this._resolver.resolveModuleFromDirIfExists(
absolutePath,
moduleName,
// required to also resolve files without leading './' directly in the path
{paths: [absolutePath]},
);
if (module) {
return module;
}
}
throw new Error(
`Cannot resolve module '${moduleName}' from paths ['${paths.join(
"', '",
)}'] from ${from}`,
);
}
try {
return this._resolveModule(from, moduleName);
} catch (err) {
const module = this._resolver.getMockModule(from, moduleName);
if (module) {
return module;
} else {
throw err;
}
}
}
private _requireResolvePaths(from: Config.Path, moduleName?: string) {
if (moduleName == null) {
throw new Error(
'The first argument to require.resolve.paths must be a string. Received null or undefined.',
);
}
if (!moduleName.length) {
throw new Error(
'The first argument to require.resolve.paths must not be the empty string.',
);
}
if (moduleName[0] === '.') {
return [path.resolve(from, '..')];
}
if (this._resolver.isCoreModule(moduleName)) {
return null;
}
return this._resolver.getModulePaths(path.resolve(from, '..'));
}
private _execModule(
localModule: InitialModule,
options: InternalModuleOptions | undefined,
moduleRegistry: ModuleRegistry,
from: Config.Path | null,
) {
// If the environment was disposed, prevent this module from being executed.
if (!this._environment.global) {
return;
}
const isInternalModule = !!(options && options.isInternalModule);
const filename = localModule.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
this._isCurrentlyExecutingManualMock = filename;
const dirname = path.dirname(filename);
localModule.children = [];
Object.defineProperty(localModule, 'parent', {
enumerable: true,
get() {
const key = from || '';
return moduleRegistry[key] || null;
},
});
localModule.paths = this._resolver.getModulePaths(dirname);
Object.defineProperty(localModule, 'require', {
value: this._createRequireImplementation(localModule, options),
});
const extraGlobals = this._config.extraGlobals || [];
const transformedFile = this._scriptTransformer.transform(
filename,
{
changedFiles: this._coverageOptions.changedFiles,
collectCoverage: this._coverageOptions.collectCoverage,
collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
extraGlobals,
isInternalModule,
},
this._cacheFS[filename],
);
if (transformedFile.sourceMapPath) {
this._sourceMapRegistry[filename] = transformedFile.sourceMapPath;
if (transformedFile.mapCoverage) {
this._needsCoverageMapped.add(filename);
}
}
const runScript = this._environment.runScript(transformedFile.script);
if (runScript === null) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
const wrapper = runScript[ScriptTransformer.EVAL_RESULT_VARIABLE];
const moduleArguments = new Set([
localModule, // module object
localModule.exports, // module exports
localModule.require, // require implementation
dirname, // __dirname
filename, // __filename
this._environment.global, // global object
this._createJestObjectFor(
filename,
localModule.require as LocalModuleRequire,
), // jest object
...extraGlobals.map(globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}
throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
}),
]);
wrapper.call(localModule.exports, ...Array.from(moduleArguments));
this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
this._currentlyExecutingModulePath = lastExecutingModulePath;
}
private _requireCoreModule(moduleName: string) {
if (moduleName === 'process') {
return this._environment.global.process;
}
return require(moduleName);
}
private _generateMock(from: Config.Path, moduleName: string) {
const modulePath =
this._resolver.resolveStubModuleName(from, moduleName) ||
this._resolveModule(from, moduleName);
if (!(modulePath in this._mockMetaDataCache)) {
// This allows us to handle circular dependencies while generating an
// automock
this._mockMetaDataCache[modulePath] = this._moduleMocker.getMetadata(
{},
) as any;
// 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 could cause issues 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(from, moduleName);
// Restore the "real" module/mock registries
this._mockRegistry = origMockRegistry;
this._moduleRegistry = origModuleRegistry;
const mockMetadata = this._moduleMocker.getMetadata(moduleExports);
if (mockMetadata == null) {
throw new Error(
`Failed to get mock metadata: ${modulePath}\n\n` +
`See: https://jestjs.io/docs/manual-mocks.html#content`,
);
}
this._mockMetaDataCache[modulePath] = mockMetadata;
}
return this._moduleMocker.generateFromMetadata(
this._mockMetaDataCache[modulePath],
);
}
private _shouldMock(from: Config.Path, moduleName: string) {
const mockPath = this._resolver.getModulePath(from, moduleName);
if (mockPath in this._virtualMocks) {
return true;
}
const explicitShouldMock = this._explicitShouldMock;
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
);
const key = from + path.delimiter + moduleID;
if (moduleID in explicitShouldMock) {
return explicitShouldMock[moduleID];
}
if (
!this._shouldAutoMock ||
this._resolver.isCoreModule(moduleName) ||
this._shouldUnmockTransitiveDependenciesCache[key]
) {
return false;
}
if (moduleID in this._shouldMockModuleCache) {
return this._shouldMockModuleCache[moduleID];
}
let modulePath;
try {
modulePath = this._resolveModule(from, moduleName);
} catch (e) {
const manualMock = this._resolver.getMockModule(from, moduleName);
if (manualMock) {
this._shouldMockModuleCache[moduleID] = true;
return true;
}
throw e;
}
if (this._unmockList && this._unmockList.test(modulePath)) {
this._shouldMockModuleCache[moduleID] = false;
return false;
}
// transitive unmocking for package managers that store flat packages (npm3)
const currentModuleID = this._resolver.getModuleID(
this._virtualMocks,
from,
);
if (
this._transitiveShouldMock[currentModuleID] === false ||
(from.includes(NODE_MODULES) &&
modulePath.includes(NODE_MODULES) &&
((this._unmockList && this._unmockList.test(from)) ||
explicitShouldMock[currentModuleID] === false))
) {
this._transitiveShouldMock[moduleID] = false;
this._shouldUnmockTransitiveDependenciesCache[key] = true;
return false;
}
return (this._shouldMockModuleCache[moduleID] = true);
}
private _createRequireImplementation(
from: InitialModule,
options?: InternalModuleOptions,
): LocalModuleRequire {
// TODO: somehow avoid having to type the arguments - they should come from `NodeRequire/LocalModuleRequire.resolve`
const resolve = (moduleName: string, options: ResolveOptions) =>
this._requireResolve(from.filename, moduleName, options);
resolve.paths = (moduleName: string) =>
this._requireResolvePaths(from.filename, moduleName);
const moduleRequire = (options && options.isInternalModule
? (moduleName: string) =>
this.requireInternalModule(from.filename, moduleName)
: this.requireModuleOrMock.bind(
this,
from.filename,
)) as LocalModuleRequire;
moduleRequire.cache = Object.create(null);
moduleRequire.extensions = Object.create(null);
moduleRequire.requireActual = this.requireActual.bind(this, from.filename);
moduleRequire.requireMock = this.requireMock.bind(this, from.filename);
moduleRequire.resolve = resolve;
Object.defineProperty(moduleRequire, 'main', {
enumerable: true,
get() {
let mainModule = from.parent;
while (
mainModule &&
mainModule.parent &&
mainModule.id !== mainModule.parent.id
) {
mainModule = mainModule.parent;
}
return mainModule;
},
});
return moduleRequire;
}
private _createJestObjectFor(
from: Config.Path,
localRequire: LocalModuleRequire,
): Jest {
const disableAutomock = () => {
this._shouldAutoMock = false;
return jestObject;
};
const enableAutomock = () => {
this._shouldAutoMock = true;
return jestObject;
};
const unmock = (moduleName: string) => {
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
);
this._explicitShouldMock[moduleID] = false;
return jestObject;
};
const deepUnmock = (moduleName: string) => {
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
);
this._explicitShouldMock[moduleID] = false;
this._transitiveShouldMock[moduleID] = false;
return jestObject;
};
const mock: Jest['mock'] = (moduleName, mockFactory, options) => {
if (mockFactory !== undefined) {
return setMockFactory(moduleName, mockFactory, options);
}
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
);
this._explicitShouldMock[moduleID] = true;
return jestObject;
};
const setMockFactory = (
moduleName: string,
mockFactory: () => unknown,
options?: {virtual?: boolean},
) => {
this.setMock(from, moduleName, mockFactory, options);
return jestObject;
};
const clearAllMocks = () => {
this.clearAllMocks();
return jestObject;
};
const resetAllMocks = () => {
this.resetAllMocks();
return jestObject;
};
const restoreAllMocks = () => {
this.restoreAllMocks();
return jestObject;
};
const useFakeTimers = () => {
this._environment.fakeTimers.useFakeTimers();
return jestObject;
};
const useRealTimers = () => {
this._environment.fakeTimers.useRealTimers();
return jestObject;
};
const resetModules = () => {
this.resetModules();
return jestObject;
};
const isolateModules = (fn: () => void) => {
this.isolateModules(fn);
return jestObject;
};
const fn = this._moduleMocker.fn.bind(this._moduleMocker);
const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker);
const setTimeout = (timeout: number) => {
if (this._environment.global.jasmine) {
this._environment.global.jasmine._DEFAULT_TIMEOUT_INTERVAL = timeout;
} else {
// @ts-ignore: https://github.com/Microsoft/TypeScript/issues/24587
this._environment.global[testTimeoutSymbol] = timeout;
}
return jestObject;
};
const retryTimes = (numTestRetries: number) => {
// @ts-ignore: https://github.com/Microsoft/TypeScript/issues/24587
this._environment.global[retryTimesSymbol] = numTestRetries;
return jestObject;
};
const _getFakeTimers = () => {
if (!this._environment.fakeTimers) {
this._logFormattedReferenceError(
'You are trying to access a property or method of the Jest environment after it has been torn down.',
);
process.exitCode = 1;
}
return this._environment.fakeTimers;
};
const jestObject: Jest = {
addMatchers: (matchers: Object) =>
this._environment.global.jasmine.addMatchers(matchers),
advanceTimersByTime: (msToRun: number) =>
_getFakeTimers().advanceTimersByTime(msToRun),
autoMockOff: disableAutomock,
autoMockOn: enableAutomock,
clearAllMocks,
clearAllTimers: () => _getFakeTimers().clearAllTimers(),
deepUnmock,
disableAutomock,
doMock: mock,
dontMock: unmock,
enableAutomock,
fn,
genMockFromModule: (moduleName: string) =>
this._generateMock(from, moduleName),
getTimerCount: () => _getFakeTimers().getTimerCount(),
isMockFunction: this._moduleMocker.isMockFunction,