UNPKG

52.7 kBJavaScriptView Raw
1'use strict';
2
3function _url() {
4 const data = require('url');
5
6 _url = function () {
7 return data;
8 };
9
10 return data;
11}
12
13function path() {
14 const data = _interopRequireWildcard(require('path'));
15
16 path = function () {
17 return data;
18 };
19
20 return data;
21}
22
23function _vm() {
24 const data = require('vm');
25
26 _vm = function () {
27 return data;
28 };
29
30 return data;
31}
32
33function nativeModule() {
34 const data = _interopRequireWildcard(require('module'));
35
36 nativeModule = function () {
37 return data;
38 };
39
40 return data;
41}
42
43function _fakeTimers() {
44 const data = require('@jest/fake-timers');
45
46 _fakeTimers = function () {
47 return data;
48 };
49
50 return data;
51}
52
53function _jestMessageUtil() {
54 const data = require('jest-message-util');
55
56 _jestMessageUtil = function () {
57 return data;
58 };
59
60 return data;
61}
62
63function _jestUtil() {
64 const data = require('jest-util');
65
66 _jestUtil = function () {
67 return data;
68 };
69
70 return data;
71}
72
73function _jestRegexUtil() {
74 const data = require('jest-regex-util');
75
76 _jestRegexUtil = function () {
77 return data;
78 };
79
80 return data;
81}
82
83function _transform() {
84 const data = require('@jest/transform');
85
86 _transform = function () {
87 return data;
88 };
89
90 return data;
91}
92
93function _collectV8Coverage() {
94 const data = require('collect-v8-coverage');
95
96 _collectV8Coverage = function () {
97 return data;
98 };
99
100 return data;
101}
102
103function fs() {
104 const data = _interopRequireWildcard(require('graceful-fs'));
105
106 fs = function () {
107 return data;
108 };
109
110 return data;
111}
112
113function _jestMock() {
114 const data = _interopRequireDefault(require('jest-mock'));
115
116 _jestMock = function () {
117 return data;
118 };
119
120 return data;
121}
122
123function _jestHasteMap() {
124 const data = _interopRequireDefault(require('jest-haste-map'));
125
126 _jestHasteMap = function () {
127 return data;
128 };
129
130 return data;
131}
132
133function _jestResolve() {
134 const data = _interopRequireDefault(require('jest-resolve'));
135
136 _jestResolve = function () {
137 return data;
138 };
139
140 return data;
141}
142
143function _jestSnapshot() {
144 const data = _interopRequireDefault(require('jest-snapshot'));
145
146 _jestSnapshot = function () {
147 return data;
148 };
149
150 return data;
151}
152
153function _stripBom() {
154 const data = _interopRequireDefault(require('strip-bom'));
155
156 _stripBom = function () {
157 return data;
158 };
159
160 return data;
161}
162
163var _helpers = require('./helpers');
164
165var _args = require('./cli/args');
166
167var _cli = require('./cli');
168
169var _Object$fromEntries;
170
171function _interopRequireDefault(obj) {
172 return obj && obj.__esModule ? obj : {default: obj};
173}
174
175function _getRequireWildcardCache() {
176 if (typeof WeakMap !== 'function') return null;
177 var cache = new WeakMap();
178 _getRequireWildcardCache = function () {
179 return cache;
180 };
181 return cache;
182}
183
184function _interopRequireWildcard(obj) {
185 if (obj && obj.__esModule) {
186 return obj;
187 }
188 if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
189 return {default: obj};
190 }
191 var cache = _getRequireWildcardCache();
192 if (cache && cache.has(obj)) {
193 return cache.get(obj);
194 }
195 var newObj = {};
196 var hasPropertyDescriptor =
197 Object.defineProperty && Object.getOwnPropertyDescriptor;
198 for (var key in obj) {
199 if (Object.prototype.hasOwnProperty.call(obj, key)) {
200 var desc = hasPropertyDescriptor
201 ? Object.getOwnPropertyDescriptor(obj, key)
202 : null;
203 if (desc && (desc.get || desc.set)) {
204 Object.defineProperty(newObj, key, desc);
205 } else {
206 newObj[key] = obj[key];
207 }
208 }
209 }
210 newObj.default = obj;
211 if (cache) {
212 cache.set(obj, newObj);
213 }
214 return newObj;
215}
216
217function _defineProperty(obj, key, value) {
218 if (key in obj) {
219 Object.defineProperty(obj, key, {
220 value: value,
221 enumerable: true,
222 configurable: true,
223 writable: true
224 });
225 } else {
226 obj[key] = value;
227 }
228 return obj;
229}
230
231const defaultTransformOptions = {
232 isInternalModule: false,
233 supportsDynamicImport: false,
234 supportsStaticESM: false
235};
236const OUTSIDE_JEST_VM_RESOLVE_OPTION = Symbol.for(
237 'OUTSIDE_JEST_VM_RESOLVE_OPTION'
238);
239const fromEntries =
240 (_Object$fromEntries = Object.fromEntries) !== null &&
241 _Object$fromEntries !== void 0
242 ? _Object$fromEntries
243 : function fromEntries(iterable) {
244 return [...iterable].reduce((obj, [key, val]) => {
245 obj[key] = val;
246 return obj;
247 }, {});
248 };
249const testTimeoutSymbol = Symbol.for('TEST_TIMEOUT_SYMBOL');
250const retryTimesSymbol = Symbol.for('RETRY_TIMES');
251const NODE_MODULES = path().sep + 'node_modules' + path().sep;
252
253const getModuleNameMapper = config => {
254 if (
255 Array.isArray(config.moduleNameMapper) &&
256 config.moduleNameMapper.length
257 ) {
258 return config.moduleNameMapper.map(([regex, moduleName]) => ({
259 moduleName,
260 regex: new RegExp(regex)
261 }));
262 }
263
264 return null;
265};
266
267const unmockRegExpCache = new WeakMap();
268const EVAL_RESULT_VARIABLE = 'Object.<anonymous>';
269const runtimeSupportsVmModules = typeof _vm().SyntheticModule === 'function';
270
271class Runtime {
272 constructor(config, environment, resolver, cacheFS = {}, coverageOptions) {
273 _defineProperty(this, '_cacheFS', void 0);
274
275 _defineProperty(this, '_config', void 0);
276
277 _defineProperty(this, '_coverageOptions', void 0);
278
279 _defineProperty(this, '_currentlyExecutingModulePath', void 0);
280
281 _defineProperty(this, '_environment', void 0);
282
283 _defineProperty(this, '_explicitShouldMock', void 0);
284
285 _defineProperty(this, '_fakeTimersImplementation', void 0);
286
287 _defineProperty(this, '_internalModuleRegistry', void 0);
288
289 _defineProperty(this, '_isCurrentlyExecutingManualMock', void 0);
290
291 _defineProperty(this, '_mockFactories', void 0);
292
293 _defineProperty(this, '_mockMetaDataCache', void 0);
294
295 _defineProperty(this, '_mockRegistry', void 0);
296
297 _defineProperty(this, '_isolatedMockRegistry', void 0);
298
299 _defineProperty(this, '_moduleMocker', void 0);
300
301 _defineProperty(this, '_isolatedModuleRegistry', void 0);
302
303 _defineProperty(this, '_moduleRegistry', void 0);
304
305 _defineProperty(this, '_esmoduleRegistry', void 0);
306
307 _defineProperty(this, '_resolver', void 0);
308
309 _defineProperty(this, '_shouldAutoMock', void 0);
310
311 _defineProperty(this, '_shouldMockModuleCache', void 0);
312
313 _defineProperty(this, '_shouldUnmockTransitiveDependenciesCache', void 0);
314
315 _defineProperty(this, '_sourceMapRegistry', void 0);
316
317 _defineProperty(this, '_scriptTransformer', void 0);
318
319 _defineProperty(this, '_fileTransforms', void 0);
320
321 _defineProperty(this, '_v8CoverageInstrumenter', void 0);
322
323 _defineProperty(this, '_v8CoverageResult', void 0);
324
325 _defineProperty(this, '_transitiveShouldMock', void 0);
326
327 _defineProperty(this, '_unmockList', void 0);
328
329 _defineProperty(this, '_virtualMocks', void 0);
330
331 _defineProperty(this, '_moduleImplementation', void 0);
332
333 _defineProperty(this, 'jestObjectCaches', void 0);
334
335 _defineProperty(this, 'jestGlobals', void 0);
336
337 _defineProperty(
338 this,
339 'unstable_shouldLoadAsEsm',
340 _jestResolve().default.unstable_shouldLoadAsEsm
341 );
342
343 this._cacheFS = new Map(Object.entries(cacheFS));
344 this._config = config;
345 this._coverageOptions = coverageOptions || {
346 changedFiles: undefined,
347 collectCoverage: false,
348 collectCoverageFrom: [],
349 collectCoverageOnlyFrom: undefined,
350 coverageProvider: 'babel',
351 sourcesRelatedToTestsInChangedFiles: undefined
352 };
353 this._currentlyExecutingModulePath = '';
354 this._environment = environment;
355 this._explicitShouldMock = new Map();
356 this._internalModuleRegistry = new Map();
357 this._isCurrentlyExecutingManualMock = null;
358 this._mockFactories = new Map();
359 this._mockRegistry = new Map(); // during setup, this cannot be null (and it's fine to explode if it is)
360
361 this._moduleMocker = this._environment.moduleMocker;
362 this._isolatedModuleRegistry = null;
363 this._isolatedMockRegistry = null;
364 this._moduleRegistry = new Map();
365 this._esmoduleRegistry = new Map();
366 this._resolver = resolver;
367 this._scriptTransformer = new (_transform().ScriptTransformer)(config);
368 this._shouldAutoMock = config.automock;
369 this._sourceMapRegistry = new Map();
370 this._fileTransforms = new Map();
371 this._virtualMocks = new Map();
372 this.jestObjectCaches = new Map();
373 this._mockMetaDataCache = new Map();
374 this._shouldMockModuleCache = new Map();
375 this._shouldUnmockTransitiveDependenciesCache = new Map();
376 this._transitiveShouldMock = new Map();
377 this._fakeTimersImplementation =
378 config.timers === 'modern'
379 ? this._environment.fakeTimersModern
380 : this._environment.fakeTimers;
381 this._unmockList = unmockRegExpCache.get(config);
382
383 if (!this._unmockList && config.unmockedModulePathPatterns) {
384 this._unmockList = new RegExp(
385 config.unmockedModulePathPatterns.join('|')
386 );
387 unmockRegExpCache.set(config, this._unmockList);
388 }
389
390 if (config.automock) {
391 const virtualMocks = fromEntries(this._virtualMocks);
392 config.setupFiles.forEach(filePath => {
393 if (filePath && filePath.includes(NODE_MODULES)) {
394 const moduleID = this._resolver.getModuleID(virtualMocks, filePath);
395
396 this._transitiveShouldMock.set(moduleID, false);
397 }
398 });
399 }
400
401 this.resetModules();
402 }
403
404 static createContext(config, options) {
405 (0, _jestUtil().createDirectory)(config.cacheDirectory);
406 const instance = Runtime.createHasteMap(config, {
407 console: options.console,
408 maxWorkers: options.maxWorkers,
409 resetCache: !config.cache,
410 watch: options.watch,
411 watchman: options.watchman
412 });
413 return instance.build().then(
414 hasteMap => ({
415 config,
416 hasteFS: hasteMap.hasteFS,
417 moduleMap: hasteMap.moduleMap,
418 resolver: Runtime.createResolver(config, hasteMap.moduleMap)
419 }),
420 error => {
421 throw error;
422 }
423 );
424 }
425
426 static createHasteMap(config, options) {
427 const ignorePatternParts = [
428 ...config.modulePathIgnorePatterns,
429 ...(options && options.watch ? config.watchPathIgnorePatterns : []),
430 config.cacheDirectory.startsWith(config.rootDir + path().sep) &&
431 config.cacheDirectory
432 ].filter(Boolean);
433 const ignorePattern =
434 ignorePatternParts.length > 0
435 ? new RegExp(ignorePatternParts.join('|'))
436 : undefined;
437 return new (_jestHasteMap().default)({
438 cacheDirectory: config.cacheDirectory,
439 computeSha1: config.haste.computeSha1,
440 console: options && options.console,
441 dependencyExtractor: config.dependencyExtractor,
442 extensions: [_jestSnapshot().default.EXTENSION].concat(
443 config.moduleFileExtensions
444 ),
445 hasteImplModulePath: config.haste.hasteImplModulePath,
446 ignorePattern,
447 maxWorkers: (options && options.maxWorkers) || 1,
448 mocksPattern: (0, _jestRegexUtil().escapePathForRegex)(
449 path().sep + '__mocks__' + path().sep
450 ),
451 name: config.name,
452 platforms: config.haste.platforms || ['ios', 'android'],
453 resetCache: options && options.resetCache,
454 retainAllFiles: false,
455 rootDir: config.rootDir,
456 roots: config.roots,
457 throwOnModuleCollision: config.haste.throwOnModuleCollision,
458 useWatchman: options && options.watchman,
459 watch: options && options.watch
460 });
461 }
462
463 static createResolver(config, moduleMap) {
464 return new (_jestResolve().default)(moduleMap, {
465 defaultPlatform: config.haste.defaultPlatform,
466 extensions: config.moduleFileExtensions.map(extension => '.' + extension),
467 hasCoreModules: true,
468 moduleDirectories: config.moduleDirectories,
469 moduleNameMapper: getModuleNameMapper(config),
470 modulePaths: config.modulePaths,
471 platforms: config.haste.platforms,
472 resolver: config.resolver,
473 rootDir: config.rootDir
474 });
475 }
476
477 static runCLI(args, info) {
478 return (0, _cli.run)(args, info);
479 }
480
481 static getCLIOptions() {
482 return _args.options;
483 } // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it
484
485 async loadEsmModule(modulePath, query = '') {
486 const cacheKey = modulePath + query;
487
488 if (!this._esmoduleRegistry.has(cacheKey)) {
489 invariant(
490 typeof this._environment.getVmContext === 'function',
491 'ES Modules are only supported if your test environment has the `getVmContext` function'
492 );
493
494 const context = this._environment.getVmContext();
495
496 invariant(context);
497
498 if (this._resolver.isCoreModule(modulePath)) {
499 const core = await this._importCoreModule(modulePath, context);
500
501 this._esmoduleRegistry.set(cacheKey, core);
502
503 return core;
504 }
505
506 const transformedCode = this.transformFile(modulePath, {
507 isInternalModule: false,
508 supportsDynamicImport: true,
509 supportsStaticESM: true
510 });
511 const module = new (_vm().SourceTextModule)(transformedCode, {
512 context,
513 identifier: modulePath,
514 importModuleDynamically: this.linkModules.bind(this),
515
516 initializeImportMeta(meta) {
517 meta.url = (0, _url().pathToFileURL)(modulePath).href;
518 }
519 });
520
521 this._esmoduleRegistry.set(
522 cacheKey, // we wanna put the linking promise in the cache so modules loaded in
523 // parallel can all await it. We then await it synchronously below, so
524 // we shouldn't get any unhandled rejections
525 module
526 .link(this.linkModules.bind(this))
527 .then(() => module.evaluate())
528 .then(() => module)
529 );
530 }
531
532 const module = this._esmoduleRegistry.get(cacheKey);
533
534 invariant(module);
535 return module;
536 }
537
538 linkModules(specifier, referencingModule) {
539 if (specifier === '@jest/globals') {
540 const fromCache = this._esmoduleRegistry.get('@jest/globals');
541
542 if (fromCache) {
543 return fromCache;
544 }
545
546 const globals = this.getGlobalsForEsm(
547 referencingModule.identifier,
548 referencingModule.context
549 );
550
551 this._esmoduleRegistry.set('@jest/globals', globals);
552
553 return globals;
554 }
555
556 const [path, query] = specifier.split('?');
557
558 const resolved = this._resolveModule(referencingModule.identifier, path);
559
560 if (
561 this._resolver.isCoreModule(resolved) ||
562 this.unstable_shouldLoadAsEsm(resolved)
563 ) {
564 return this.loadEsmModule(resolved, query);
565 }
566
567 return this.loadCjsAsEsm(
568 referencingModule.identifier,
569 resolved,
570 referencingModule.context
571 );
572 }
573
574 async unstable_importModule(from, moduleName) {
575 invariant(
576 runtimeSupportsVmModules,
577 'You need to run with a version of node that supports ES Modules in the VM API.'
578 );
579 const [path, query] = (moduleName !== null && moduleName !== void 0
580 ? moduleName
581 : ''
582 ).split('?');
583
584 const modulePath = this._resolveModule(from, path);
585
586 return this.loadEsmModule(modulePath, query);
587 }
588
589 async loadCjsAsEsm(from, modulePath, context) {
590 // CJS loaded via `import` should share cache with other CJS: https://github.com/nodejs/modules/issues/503
591 const cjs = this.requireModuleOrMock(from, modulePath);
592 const module = new (_vm().SyntheticModule)(
593 ['default'],
594 function () {
595 // @ts-expect-error: TS doesn't know what `this` is
596 this.setExport('default', cjs);
597 },
598 {
599 context,
600 identifier: modulePath
601 }
602 );
603 await module.link(() => {
604 throw new Error('This should never happen');
605 });
606 await module.evaluate();
607 return module;
608 }
609
610 requireModule(from, moduleName, options, isRequireActual) {
611 const moduleID = this._resolver.getModuleID(
612 fromEntries(this._virtualMocks),
613 from,
614 moduleName
615 );
616
617 let modulePath; // Some old tests rely on this mocking behavior. Ideally we'll change this
618 // to be more explicit.
619
620 const moduleResource = moduleName && this._resolver.getModule(moduleName);
621
622 const manualMock =
623 moduleName && this._resolver.getMockModule(from, moduleName);
624
625 if (
626 !(options === null || options === void 0
627 ? void 0
628 : options.isInternalModule) &&
629 !isRequireActual &&
630 !moduleResource &&
631 manualMock &&
632 manualMock !== this._isCurrentlyExecutingManualMock &&
633 this._explicitShouldMock.get(moduleID) !== false
634 ) {
635 modulePath = manualMock;
636 }
637
638 if (moduleName && this._resolver.isCoreModule(moduleName)) {
639 return this._requireCoreModule(moduleName);
640 }
641
642 if (!modulePath) {
643 modulePath = this._resolveModule(from, moduleName);
644 }
645
646 let moduleRegistry;
647
648 if (
649 options === null || options === void 0 ? void 0 : options.isInternalModule
650 ) {
651 moduleRegistry = this._internalModuleRegistry;
652 } else {
653 if (
654 this._moduleRegistry.get(modulePath) ||
655 !this._isolatedModuleRegistry
656 ) {
657 moduleRegistry = this._moduleRegistry;
658 } else {
659 moduleRegistry = this._isolatedModuleRegistry;
660 }
661 }
662
663 const module = moduleRegistry.get(modulePath);
664
665 if (module) {
666 return module.exports;
667 } // We must register the pre-allocated module object first so that any
668 // circular dependencies that may arise while evaluating the module can
669 // be satisfied.
670
671 const localModule = {
672 children: [],
673 exports: {},
674 filename: modulePath,
675 id: modulePath,
676 loaded: false
677 };
678 moduleRegistry.set(modulePath, localModule);
679
680 this._loadModule(
681 localModule,
682 from,
683 moduleName,
684 modulePath,
685 options,
686 moduleRegistry
687 );
688
689 return localModule.exports;
690 }
691
692 requireInternalModule(from, to) {
693 if (to) {
694 const outsideJestVmPath = (0, _helpers.decodePossibleOutsideJestVmPath)(
695 to
696 );
697
698 if (outsideJestVmPath) {
699 return require(outsideJestVmPath);
700 }
701 }
702
703 return this.requireModule(from, to, {
704 isInternalModule: true,
705 supportsDynamicImport: false,
706 supportsStaticESM: false
707 });
708 }
709
710 requireActual(from, moduleName) {
711 return this.requireModule(from, moduleName, undefined, true);
712 }
713
714 requireMock(from, moduleName) {
715 const moduleID = this._resolver.getModuleID(
716 fromEntries(this._virtualMocks),
717 from,
718 moduleName
719 );
720
721 if (
722 this._isolatedMockRegistry &&
723 this._isolatedMockRegistry.get(moduleID)
724 ) {
725 return this._isolatedMockRegistry.get(moduleID);
726 } else if (this._mockRegistry.get(moduleID)) {
727 return this._mockRegistry.get(moduleID);
728 }
729
730 const mockRegistry = this._isolatedMockRegistry || this._mockRegistry;
731
732 if (this._mockFactories.has(moduleID)) {
733 // has check above makes this ok
734 const module = this._mockFactories.get(moduleID)();
735
736 mockRegistry.set(moduleID, module);
737 return module;
738 }
739
740 const manualMockOrStub = this._resolver.getMockModule(from, moduleName);
741
742 let modulePath =
743 this._resolver.getMockModule(from, moduleName) ||
744 this._resolveModule(from, moduleName);
745
746 let isManualMock =
747 manualMockOrStub &&
748 !this._resolver.resolveStubModuleName(from, moduleName);
749
750 if (!isManualMock) {
751 // If the actual module file has a __mocks__ dir sitting immediately next
752 // to it, look to see if there is a manual mock for this file.
753 //
754 // subDir1/my_module.js
755 // subDir1/__mocks__/my_module.js
756 // subDir2/my_module.js
757 // subDir2/__mocks__/my_module.js
758 //
759 // Where some other module does a relative require into each of the
760 // respective subDir{1,2} directories and expects a manual mock
761 // corresponding to that particular my_module.js file.
762 const moduleDir = path().dirname(modulePath);
763 const moduleFileName = path().basename(modulePath);
764 const potentialManualMock = path().join(
765 moduleDir,
766 '__mocks__',
767 moduleFileName
768 );
769
770 if (fs().existsSync(potentialManualMock)) {
771 isManualMock = true;
772 modulePath = potentialManualMock;
773 }
774 }
775
776 if (isManualMock) {
777 const localModule = {
778 children: [],
779 exports: {},
780 filename: modulePath,
781 id: modulePath,
782 loaded: false
783 };
784
785 this._loadModule(
786 localModule,
787 from,
788 moduleName,
789 modulePath,
790 undefined,
791 mockRegistry
792 );
793
794 mockRegistry.set(moduleID, localModule.exports);
795 } else {
796 // Look for a real module to generate an automock from
797 mockRegistry.set(moduleID, this._generateMock(from, moduleName));
798 }
799
800 return mockRegistry.get(moduleID);
801 }
802
803 _loadModule(
804 localModule,
805 from,
806 moduleName,
807 modulePath,
808 options,
809 moduleRegistry
810 ) {
811 if (path().extname(modulePath) === '.json') {
812 const text = (0, _stripBom().default)(this.readFile(modulePath));
813
814 const transformedFile = this._scriptTransformer.transformJson(
815 modulePath,
816 this._getFullTransformationOptions(options),
817 text
818 );
819
820 localModule.exports = this._environment.global.JSON.parse(
821 transformedFile
822 );
823 } else if (path().extname(modulePath) === '.node') {
824 localModule.exports = require(modulePath);
825 } else {
826 // Only include the fromPath if a moduleName is given. Else treat as root.
827 const fromPath = moduleName ? from : null;
828
829 this._execModule(localModule, options, moduleRegistry, fromPath);
830 }
831
832 localModule.loaded = true;
833 }
834
835 _getFullTransformationOptions(options = defaultTransformOptions) {
836 return {...options, ...this._coverageOptions};
837 }
838
839 requireModuleOrMock(from, moduleName) {
840 // this module is unmockable
841 if (moduleName === '@jest/globals') {
842 // @ts-expect-error: we don't care that it's not assignable to T
843 return this.getGlobalsForCjs(from);
844 }
845
846 try {
847 if (this._shouldMock(from, moduleName)) {
848 return this.requireMock(from, moduleName);
849 } else {
850 return this.requireModule(from, moduleName);
851 }
852 } catch (e) {
853 const moduleNotFound = _jestResolve().default.tryCastModuleNotFoundError(
854 e
855 );
856
857 if (moduleNotFound) {
858 if (
859 moduleNotFound.siblingWithSimilarExtensionFound === null ||
860 moduleNotFound.siblingWithSimilarExtensionFound === undefined
861 ) {
862 moduleNotFound.hint = (0, _helpers.findSiblingsWithFileExtension)(
863 this._config.moduleFileExtensions,
864 from,
865 moduleNotFound.moduleName || moduleName
866 );
867 moduleNotFound.siblingWithSimilarExtensionFound = Boolean(
868 moduleNotFound.hint
869 );
870 }
871
872 moduleNotFound.buildMessage(this._config.rootDir);
873 throw moduleNotFound;
874 }
875
876 throw e;
877 }
878 }
879
880 isolateModules(fn) {
881 if (this._isolatedModuleRegistry || this._isolatedMockRegistry) {
882 throw new Error(
883 'isolateModules cannot be nested inside another isolateModules.'
884 );
885 }
886
887 this._isolatedModuleRegistry = new Map();
888 this._isolatedMockRegistry = new Map();
889
890 try {
891 fn();
892 } finally {
893 var _this$_isolatedModule, _this$_isolatedMockRe;
894
895 // might be cleared within the callback
896 (_this$_isolatedModule = this._isolatedModuleRegistry) === null ||
897 _this$_isolatedModule === void 0
898 ? void 0
899 : _this$_isolatedModule.clear();
900 (_this$_isolatedMockRe = this._isolatedMockRegistry) === null ||
901 _this$_isolatedMockRe === void 0
902 ? void 0
903 : _this$_isolatedMockRe.clear();
904 this._isolatedModuleRegistry = null;
905 this._isolatedMockRegistry = null;
906 }
907 }
908
909 resetModules() {
910 var _this$_isolatedModule2, _this$_isolatedMockRe2;
911
912 (_this$_isolatedModule2 = this._isolatedModuleRegistry) === null ||
913 _this$_isolatedModule2 === void 0
914 ? void 0
915 : _this$_isolatedModule2.clear();
916 (_this$_isolatedMockRe2 = this._isolatedMockRegistry) === null ||
917 _this$_isolatedMockRe2 === void 0
918 ? void 0
919 : _this$_isolatedMockRe2.clear();
920 this._isolatedModuleRegistry = null;
921 this._isolatedMockRegistry = null;
922
923 this._mockRegistry.clear();
924
925 this._moduleRegistry.clear();
926
927 this._esmoduleRegistry.clear();
928
929 if (this._environment) {
930 if (this._environment.global) {
931 const envGlobal = this._environment.global;
932 Object.keys(envGlobal).forEach(key => {
933 const globalMock = envGlobal[key];
934
935 if (
936 ((typeof globalMock === 'object' && globalMock !== null) ||
937 typeof globalMock === 'function') &&
938 globalMock._isMockFunction === true
939 ) {
940 globalMock.mockClear();
941 }
942 });
943 }
944
945 if (this._environment.fakeTimers) {
946 this._environment.fakeTimers.clearAllTimers();
947 }
948 }
949 }
950
951 async collectV8Coverage() {
952 this._v8CoverageInstrumenter = new (_collectV8Coverage().CoverageInstrumenter)();
953 await this._v8CoverageInstrumenter.startInstrumenting();
954 }
955
956 async stopCollectingV8Coverage() {
957 if (!this._v8CoverageInstrumenter) {
958 throw new Error('You need to call `collectV8Coverage` first.');
959 }
960
961 this._v8CoverageResult = await this._v8CoverageInstrumenter.stopInstrumenting();
962 }
963
964 getAllCoverageInfoCopy() {
965 return (0, _jestUtil().deepCyclicCopy)(
966 this._environment.global.__coverage__
967 );
968 }
969
970 getAllV8CoverageInfoCopy() {
971 if (!this._v8CoverageResult) {
972 throw new Error('You need to `stopCollectingV8Coverage` first');
973 }
974
975 return this._v8CoverageResult
976 .filter(res => res.url.startsWith('file://'))
977 .map(res => ({...res, url: (0, _url().fileURLToPath)(res.url)}))
978 .filter(
979 (
980 res // TODO: will this work on windows? It might be better if `shouldInstrument` deals with it anyways
981 ) =>
982 res.url.startsWith(this._config.rootDir) &&
983 this._fileTransforms.has(res.url) &&
984 (0, _transform().shouldInstrument)(
985 res.url,
986 this._coverageOptions,
987 this._config
988 )
989 )
990 .map(result => {
991 const transformedFile = this._fileTransforms.get(result.url);
992
993 return {
994 codeTransformResult: transformedFile,
995 result
996 };
997 });
998 } // TODO - remove in Jest 27
999
1000 getSourceMapInfo(_coveredFiles) {
1001 return {};
1002 }
1003
1004 getSourceMaps() {
1005 return fromEntries(this._sourceMapRegistry);
1006 }
1007
1008 setMock(from, moduleName, mockFactory, options) {
1009 if (options === null || options === void 0 ? void 0 : options.virtual) {
1010 const mockPath = this._resolver.getModulePath(from, moduleName);
1011
1012 this._virtualMocks.set(mockPath, true);
1013 }
1014
1015 const moduleID = this._resolver.getModuleID(
1016 fromEntries(this._virtualMocks),
1017 from,
1018 moduleName
1019 );
1020
1021 this._explicitShouldMock.set(moduleID, true);
1022
1023 this._mockFactories.set(moduleID, mockFactory);
1024 }
1025
1026 restoreAllMocks() {
1027 this._moduleMocker.restoreAllMocks();
1028 }
1029
1030 resetAllMocks() {
1031 this._moduleMocker.resetAllMocks();
1032 }
1033
1034 clearAllMocks() {
1035 this._moduleMocker.clearAllMocks();
1036 }
1037
1038 teardown() {
1039 this.restoreAllMocks();
1040 this.resetAllMocks();
1041 this.resetModules();
1042
1043 this._internalModuleRegistry.clear();
1044
1045 this._mockFactories.clear();
1046
1047 this._mockMetaDataCache.clear();
1048
1049 this._shouldMockModuleCache.clear();
1050
1051 this._shouldUnmockTransitiveDependenciesCache.clear();
1052
1053 this._explicitShouldMock.clear();
1054
1055 this._transitiveShouldMock.clear();
1056
1057 this._virtualMocks.clear();
1058
1059 this._cacheFS.clear();
1060
1061 this._unmockList = undefined;
1062
1063 this._sourceMapRegistry.clear();
1064
1065 this._fileTransforms.clear();
1066
1067 this.jestObjectCaches.clear();
1068 this._v8CoverageResult = [];
1069 this._v8CoverageInstrumenter = undefined;
1070 this._moduleImplementation = undefined;
1071 }
1072
1073 _resolveModule(from, to) {
1074 return to ? this._resolver.resolveModule(from, to) : from;
1075 }
1076
1077 _requireResolve(from, moduleName, options = {}) {
1078 if (moduleName == null) {
1079 throw new Error(
1080 'The first argument to require.resolve must be a string. Received null or undefined.'
1081 );
1082 }
1083
1084 const {paths} = options;
1085
1086 if (paths) {
1087 for (const p of paths) {
1088 const absolutePath = path().resolve(from, '..', p);
1089
1090 const module = this._resolver.resolveModuleFromDirIfExists(
1091 absolutePath,
1092 moduleName, // required to also resolve files without leading './' directly in the path
1093 {
1094 paths: [absolutePath]
1095 }
1096 );
1097
1098 if (module) {
1099 return module;
1100 }
1101 }
1102
1103 throw new (_jestResolve().default.ModuleNotFoundError)(
1104 `Cannot resolve module '${moduleName}' from paths ['${paths.join(
1105 "', '"
1106 )}'] from ${from}`
1107 );
1108 }
1109
1110 try {
1111 return this._resolveModule(from, moduleName);
1112 } catch (err) {
1113 const module = this._resolver.getMockModule(from, moduleName);
1114
1115 if (module) {
1116 return module;
1117 } else {
1118 throw err;
1119 }
1120 }
1121 }
1122
1123 _requireResolvePaths(from, moduleName) {
1124 if (moduleName == null) {
1125 throw new Error(
1126 'The first argument to require.resolve.paths must be a string. Received null or undefined.'
1127 );
1128 }
1129
1130 if (!moduleName.length) {
1131 throw new Error(
1132 'The first argument to require.resolve.paths must not be the empty string.'
1133 );
1134 }
1135
1136 if (moduleName[0] === '.') {
1137 return [path().resolve(from, '..')];
1138 }
1139
1140 if (this._resolver.isCoreModule(moduleName)) {
1141 return null;
1142 }
1143
1144 return this._resolver.getModulePaths(path().resolve(from, '..'));
1145 }
1146
1147 _execModule(localModule, options, moduleRegistry, from) {
1148 // If the environment was disposed, prevent this module from being executed.
1149 if (!this._environment.global) {
1150 return;
1151 }
1152
1153 const filename = localModule.filename;
1154 const lastExecutingModulePath = this._currentlyExecutingModulePath;
1155 this._currentlyExecutingModulePath = filename;
1156 const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
1157 this._isCurrentlyExecutingManualMock = filename;
1158 const dirname = path().dirname(filename);
1159 localModule.children = [];
1160 Object.defineProperty(localModule, 'parent', {
1161 enumerable: true,
1162
1163 get() {
1164 const key = from || '';
1165 return moduleRegistry.get(key) || null;
1166 }
1167 });
1168 localModule.paths = this._resolver.getModulePaths(dirname);
1169 Object.defineProperty(localModule, 'require', {
1170 value: this._createRequireImplementation(localModule, options)
1171 });
1172 const transformedCode = this.transformFile(filename, options);
1173 let compiledFunction = null;
1174 const script = this.createScriptFromCode(transformedCode, filename);
1175 let runScript = null; // Use this if available instead of deprecated `JestEnvironment.runScript`
1176
1177 if (typeof this._environment.getVmContext === 'function') {
1178 const vmContext = this._environment.getVmContext();
1179
1180 if (vmContext) {
1181 runScript = script.runInContext(vmContext, {
1182 filename
1183 });
1184 }
1185 } else {
1186 runScript = this._environment.runScript(script);
1187 }
1188
1189 if (runScript !== null) {
1190 compiledFunction = runScript[EVAL_RESULT_VARIABLE];
1191 }
1192
1193 if (compiledFunction === null) {
1194 this._logFormattedReferenceError(
1195 'You are trying to `import` a file after the Jest environment has been torn down.'
1196 );
1197
1198 process.exitCode = 1;
1199 return;
1200 }
1201
1202 const jestObject = this._createJestObjectFor(filename);
1203
1204 this.jestObjectCaches.set(filename, jestObject);
1205 const lastArgs = [
1206 this._config.injectGlobals ? jestObject : undefined, // jest object
1207 this._config.extraGlobals.map(globalVariable => {
1208 if (this._environment.global[globalVariable]) {
1209 return this._environment.global[globalVariable];
1210 }
1211
1212 throw new Error(
1213 `You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`
1214 );
1215 })
1216 ];
1217
1218 try {
1219 compiledFunction.call(
1220 localModule.exports,
1221 localModule, // module object
1222 localModule.exports, // module exports
1223 localModule.require, // require implementation
1224 dirname, // __dirname
1225 filename, // __filename
1226 this._environment.global, // global object
1227 ...lastArgs.filter(notEmpty)
1228 );
1229 } catch (error) {
1230 this.handleExecutionError(error, localModule);
1231 }
1232
1233 this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
1234 this._currentlyExecutingModulePath = lastExecutingModulePath;
1235 }
1236
1237 transformFile(filename, options) {
1238 const source = this.readFile(filename);
1239
1240 if (
1241 options === null || options === void 0 ? void 0 : options.isInternalModule
1242 ) {
1243 return source;
1244 }
1245
1246 const transformedFile = this._scriptTransformer.transform(
1247 filename,
1248 this._getFullTransformationOptions(options),
1249 source
1250 );
1251
1252 this._fileTransforms.set(filename, {
1253 ...transformedFile,
1254 wrapperLength: this.constructModuleWrapperStart().length
1255 });
1256
1257 if (transformedFile.sourceMapPath) {
1258 this._sourceMapRegistry.set(filename, transformedFile.sourceMapPath);
1259 }
1260
1261 return transformedFile.code;
1262 }
1263
1264 createScriptFromCode(scriptSource, filename) {
1265 try {
1266 return new (_vm().Script)(this.wrapCodeInModuleWrapper(scriptSource), {
1267 displayErrors: true,
1268 filename: this._resolver.isCoreModule(filename)
1269 ? `jest-nodejs-core-${filename}`
1270 : filename
1271 });
1272 } catch (e) {
1273 throw (0, _transform().handlePotentialSyntaxError)(e);
1274 }
1275 }
1276
1277 _requireCoreModule(moduleName) {
1278 if (moduleName === 'process') {
1279 return this._environment.global.process;
1280 }
1281
1282 if (moduleName === 'module') {
1283 return this._getMockedNativeModule();
1284 }
1285
1286 return require(moduleName);
1287 }
1288
1289 _importCoreModule(moduleName, context) {
1290 const required = this._requireCoreModule(moduleName);
1291
1292 return new (_vm().SyntheticModule)(
1293 ['default', ...Object.keys(required)],
1294 function () {
1295 // @ts-expect-error: TS doesn't know what `this` is
1296 this.setExport('default', required);
1297 Object.entries(required).forEach(([key, value]) => {
1298 // @ts-expect-error: TS doesn't know what `this` is
1299 this.setExport(key, value);
1300 });
1301 }, // should identifier be `node://${moduleName}`?
1302 {
1303 context,
1304 identifier: moduleName
1305 }
1306 );
1307 }
1308
1309 _getMockedNativeModule() {
1310 if (this._moduleImplementation) {
1311 return this._moduleImplementation;
1312 }
1313
1314 const createRequire = modulePath => {
1315 const filename =
1316 typeof modulePath === 'string'
1317 ? modulePath.startsWith('file:///')
1318 ? (0, _url().fileURLToPath)(new (_url().URL)(modulePath))
1319 : modulePath
1320 : (0, _url().fileURLToPath)(modulePath);
1321
1322 if (!path().isAbsolute(filename)) {
1323 const error = new TypeError(
1324 `The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received '${filename}'`
1325 ); // @ts-expect-error
1326
1327 error.code = 'ERR_INVALID_ARG_TYPE';
1328 throw error;
1329 }
1330
1331 return this._createRequireImplementation({
1332 children: [],
1333 exports: {},
1334 filename,
1335 id: filename,
1336 loaded: false
1337 });
1338 }; // should we implement the class ourselves?
1339
1340 class Module extends nativeModule().Module {}
1341
1342 Object.entries(nativeModule().Module).forEach(([key, value]) => {
1343 // @ts-expect-error
1344 Module[key] = value;
1345 });
1346 Module.Module = Module;
1347
1348 if ('createRequire' in nativeModule()) {
1349 Module.createRequire = createRequire;
1350 }
1351
1352 if ('createRequireFromPath' in nativeModule()) {
1353 Module.createRequireFromPath = function createRequireFromPath(filename) {
1354 if (typeof filename !== 'string') {
1355 const error = new TypeError(
1356 `The argument 'filename' must be string. Received '${filename}'.${
1357 filename instanceof _url().URL
1358 ? ' Use createRequire for URL filename.'
1359 : ''
1360 }`
1361 ); // @ts-expect-error
1362
1363 error.code = 'ERR_INVALID_ARG_TYPE';
1364 throw error;
1365 }
1366
1367 return createRequire(filename);
1368 };
1369 }
1370
1371 if ('syncBuiltinESMExports' in nativeModule()) {
1372 Module.syncBuiltinESMExports = function syncBuiltinESMExports() {};
1373 }
1374
1375 this._moduleImplementation = Module;
1376 return Module;
1377 }
1378
1379 _generateMock(from, moduleName) {
1380 const modulePath =
1381 this._resolver.resolveStubModuleName(from, moduleName) ||
1382 this._resolveModule(from, moduleName);
1383
1384 if (!this._mockMetaDataCache.has(modulePath)) {
1385 // This allows us to handle circular dependencies while generating an
1386 // automock
1387 this._mockMetaDataCache.set(
1388 modulePath,
1389 this._moduleMocker.getMetadata({}) || {}
1390 ); // In order to avoid it being possible for automocking to potentially
1391 // cause side-effects within the module environment, we need to execute
1392 // the module in isolation. This could cause issues if the module being
1393 // mocked has calls into side-effectful APIs on another module.
1394
1395 const origMockRegistry = this._mockRegistry;
1396 const origModuleRegistry = this._moduleRegistry;
1397 this._mockRegistry = new Map();
1398 this._moduleRegistry = new Map();
1399 const moduleExports = this.requireModule(from, moduleName); // Restore the "real" module/mock registries
1400
1401 this._mockRegistry = origMockRegistry;
1402 this._moduleRegistry = origModuleRegistry;
1403
1404 const mockMetadata = this._moduleMocker.getMetadata(moduleExports);
1405
1406 if (mockMetadata == null) {
1407 throw new Error(
1408 `Failed to get mock metadata: ${modulePath}\n\n` +
1409 `See: https://jestjs.io/docs/manual-mocks.html#content`
1410 );
1411 }
1412
1413 this._mockMetaDataCache.set(modulePath, mockMetadata);
1414 }
1415
1416 return this._moduleMocker.generateFromMetadata(
1417 // added above if missing
1418 this._mockMetaDataCache.get(modulePath)
1419 );
1420 }
1421
1422 _shouldMock(from, moduleName) {
1423 const explicitShouldMock = this._explicitShouldMock;
1424
1425 const moduleID = this._resolver.getModuleID(
1426 fromEntries(this._virtualMocks),
1427 from,
1428 moduleName
1429 );
1430
1431 const key = from + path().delimiter + moduleID;
1432
1433 if (explicitShouldMock.has(moduleID)) {
1434 // guaranteed by `has` above
1435 return explicitShouldMock.get(moduleID);
1436 }
1437
1438 if (
1439 !this._shouldAutoMock ||
1440 this._resolver.isCoreModule(moduleName) ||
1441 this._shouldUnmockTransitiveDependenciesCache.get(key)
1442 ) {
1443 return false;
1444 }
1445
1446 if (this._shouldMockModuleCache.has(moduleID)) {
1447 // guaranteed by `has` above
1448 return this._shouldMockModuleCache.get(moduleID);
1449 }
1450
1451 let modulePath;
1452
1453 try {
1454 modulePath = this._resolveModule(from, moduleName);
1455 } catch (e) {
1456 const manualMock = this._resolver.getMockModule(from, moduleName);
1457
1458 if (manualMock) {
1459 this._shouldMockModuleCache.set(moduleID, true);
1460
1461 return true;
1462 }
1463
1464 throw e;
1465 }
1466
1467 if (this._unmockList && this._unmockList.test(modulePath)) {
1468 this._shouldMockModuleCache.set(moduleID, false);
1469
1470 return false;
1471 } // transitive unmocking for package managers that store flat packages (npm3)
1472
1473 const currentModuleID = this._resolver.getModuleID(
1474 fromEntries(this._virtualMocks),
1475 from
1476 );
1477
1478 if (
1479 this._transitiveShouldMock.get(currentModuleID) === false ||
1480 (from.includes(NODE_MODULES) &&
1481 modulePath.includes(NODE_MODULES) &&
1482 ((this._unmockList && this._unmockList.test(from)) ||
1483 explicitShouldMock.get(currentModuleID) === false))
1484 ) {
1485 this._transitiveShouldMock.set(moduleID, false);
1486
1487 this._shouldUnmockTransitiveDependenciesCache.set(key, true);
1488
1489 return false;
1490 }
1491
1492 this._shouldMockModuleCache.set(moduleID, true);
1493
1494 return true;
1495 }
1496
1497 _createRequireImplementation(from, options) {
1498 const resolve = (moduleName, resolveOptions) => {
1499 const resolved = this._requireResolve(
1500 from.filename,
1501 moduleName,
1502 resolveOptions
1503 );
1504
1505 if (
1506 (resolveOptions === null || resolveOptions === void 0
1507 ? void 0
1508 : resolveOptions[OUTSIDE_JEST_VM_RESOLVE_OPTION]) &&
1509 (options === null || options === void 0
1510 ? void 0
1511 : options.isInternalModule)
1512 ) {
1513 return (0, _helpers.createOutsideJestVmPath)(resolved);
1514 }
1515
1516 return resolved;
1517 };
1518
1519 resolve.paths = moduleName =>
1520 this._requireResolvePaths(from.filename, moduleName);
1521
1522 const moduleRequire = (
1523 options === null || options === void 0 ? void 0 : options.isInternalModule
1524 )
1525 ? moduleName => this.requireInternalModule(from.filename, moduleName)
1526 : this.requireModuleOrMock.bind(this, from.filename);
1527 moduleRequire.extensions = Object.create(null);
1528 moduleRequire.resolve = resolve;
1529
1530 moduleRequire.cache = (() => {
1531 // TODO: consider warning somehow that this does nothing. We should support deletions, anyways
1532 const notPermittedMethod = () => true;
1533
1534 return new Proxy(Object.create(null), {
1535 defineProperty: notPermittedMethod,
1536 deleteProperty: notPermittedMethod,
1537 get: (_target, key) =>
1538 typeof key === 'string' ? this._moduleRegistry.get(key) : undefined,
1539
1540 getOwnPropertyDescriptor() {
1541 return {
1542 configurable: true,
1543 enumerable: true
1544 };
1545 },
1546
1547 has: (_target, key) =>
1548 typeof key === 'string' && this._moduleRegistry.has(key),
1549 ownKeys: () => Array.from(this._moduleRegistry.keys()),
1550 set: notPermittedMethod
1551 });
1552 })();
1553
1554 Object.defineProperty(moduleRequire, 'main', {
1555 enumerable: true,
1556
1557 get() {
1558 let mainModule = from.parent;
1559
1560 while (
1561 mainModule &&
1562 mainModule.parent &&
1563 mainModule.id !== mainModule.parent.id
1564 ) {
1565 mainModule = mainModule.parent;
1566 }
1567
1568 return mainModule;
1569 }
1570 });
1571 return moduleRequire;
1572 }
1573
1574 _createJestObjectFor(from) {
1575 const disableAutomock = () => {
1576 this._shouldAutoMock = false;
1577 return jestObject;
1578 };
1579
1580 const enableAutomock = () => {
1581 this._shouldAutoMock = true;
1582 return jestObject;
1583 };
1584
1585 const unmock = moduleName => {
1586 const moduleID = this._resolver.getModuleID(
1587 fromEntries(this._virtualMocks),
1588 from,
1589 moduleName
1590 );
1591
1592 this._explicitShouldMock.set(moduleID, false);
1593
1594 return jestObject;
1595 };
1596
1597 const deepUnmock = moduleName => {
1598 const moduleID = this._resolver.getModuleID(
1599 fromEntries(this._virtualMocks),
1600 from,
1601 moduleName
1602 );
1603
1604 this._explicitShouldMock.set(moduleID, false);
1605
1606 this._transitiveShouldMock.set(moduleID, false);
1607
1608 return jestObject;
1609 };
1610
1611 const mock = (moduleName, mockFactory, options) => {
1612 if (mockFactory !== undefined) {
1613 return setMockFactory(moduleName, mockFactory, options);
1614 }
1615
1616 const moduleID = this._resolver.getModuleID(
1617 fromEntries(this._virtualMocks),
1618 from,
1619 moduleName
1620 );
1621
1622 this._explicitShouldMock.set(moduleID, true);
1623
1624 return jestObject;
1625 };
1626
1627 const setMockFactory = (moduleName, mockFactory, options) => {
1628 this.setMock(from, moduleName, mockFactory, options);
1629 return jestObject;
1630 };
1631
1632 const clearAllMocks = () => {
1633 this.clearAllMocks();
1634 return jestObject;
1635 };
1636
1637 const resetAllMocks = () => {
1638 this.resetAllMocks();
1639 return jestObject;
1640 };
1641
1642 const restoreAllMocks = () => {
1643 this.restoreAllMocks();
1644 return jestObject;
1645 };
1646
1647 const _getFakeTimers = () => {
1648 if (
1649 !(this._environment.fakeTimers || this._environment.fakeTimersModern)
1650 ) {
1651 this._logFormattedReferenceError(
1652 'You are trying to access a property or method of the Jest environment after it has been torn down.'
1653 );
1654
1655 process.exitCode = 1;
1656 }
1657
1658 return this._fakeTimersImplementation;
1659 };
1660
1661 const useFakeTimers = (type = 'legacy') => {
1662 if (type === 'modern') {
1663 this._fakeTimersImplementation = this._environment.fakeTimersModern;
1664 } else {
1665 this._fakeTimersImplementation = this._environment.fakeTimers;
1666 }
1667
1668 this._fakeTimersImplementation.useFakeTimers();
1669
1670 return jestObject;
1671 };
1672
1673 const useRealTimers = () => {
1674 _getFakeTimers().useRealTimers();
1675
1676 return jestObject;
1677 };
1678
1679 const resetModules = () => {
1680 this.resetModules();
1681 return jestObject;
1682 };
1683
1684 const isolateModules = fn => {
1685 this.isolateModules(fn);
1686 return jestObject;
1687 };
1688
1689 const fn = this._moduleMocker.fn.bind(this._moduleMocker);
1690
1691 const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker);
1692
1693 const setTimeout = timeout => {
1694 if (this._environment.global.jasmine) {
1695 this._environment.global.jasmine._DEFAULT_TIMEOUT_INTERVAL = timeout;
1696 } else {
1697 // @ts-expect-error: https://github.com/Microsoft/TypeScript/issues/24587
1698 this._environment.global[testTimeoutSymbol] = timeout;
1699 }
1700
1701 return jestObject;
1702 };
1703
1704 const retryTimes = numTestRetries => {
1705 // @ts-expect-error: https://github.com/Microsoft/TypeScript/issues/24587
1706 this._environment.global[retryTimesSymbol] = numTestRetries;
1707 return jestObject;
1708 };
1709
1710 const jestObject = {
1711 addMatchers: matchers =>
1712 this._environment.global.jasmine.addMatchers(matchers),
1713 advanceTimersByTime: msToRun =>
1714 _getFakeTimers().advanceTimersByTime(msToRun),
1715 advanceTimersToNextTimer: steps =>
1716 _getFakeTimers().advanceTimersToNextTimer(steps),
1717 autoMockOff: disableAutomock,
1718 autoMockOn: enableAutomock,
1719 clearAllMocks,
1720 clearAllTimers: () => _getFakeTimers().clearAllTimers(),
1721 createMockFromModule: moduleName => this._generateMock(from, moduleName),
1722 deepUnmock,
1723 disableAutomock,
1724 doMock: mock,
1725 dontMock: unmock,
1726 enableAutomock,
1727 fn,
1728 genMockFromModule: moduleName => this._generateMock(from, moduleName),
1729 getRealSystemTime: () => {
1730 const fakeTimers = _getFakeTimers();
1731
1732 if (fakeTimers instanceof _fakeTimers().ModernFakeTimers) {
1733 return fakeTimers.getRealSystemTime();
1734 } else {
1735 throw new TypeError(
1736 'getRealSystemTime is not available when not using modern timers'
1737 );
1738 }
1739 },
1740 getTimerCount: () => _getFakeTimers().getTimerCount(),
1741 isMockFunction: this._moduleMocker.isMockFunction,
1742 isolateModules,
1743 mock,
1744 requireActual: this.requireActual.bind(this, from),
1745 requireMock: this.requireMock.bind(this, from),
1746 resetAllMocks,
1747 resetModuleRegistry: resetModules,
1748 resetModules,
1749 restoreAllMocks,
1750 retryTimes,
1751 runAllImmediates: () => {
1752 const fakeTimers = _getFakeTimers();
1753
1754 if (fakeTimers instanceof _fakeTimers().LegacyFakeTimers) {
1755 fakeTimers.runAllImmediates();
1756 } else {
1757 throw new TypeError(
1758 'runAllImmediates is not available when using modern timers'
1759 );
1760 }
1761 },
1762 runAllTicks: () => _getFakeTimers().runAllTicks(),
1763 runAllTimers: () => _getFakeTimers().runAllTimers(),
1764 runOnlyPendingTimers: () => _getFakeTimers().runOnlyPendingTimers(),
1765 runTimersToTime: msToRun => _getFakeTimers().advanceTimersByTime(msToRun),
1766 setMock: (moduleName, mock) => setMockFactory(moduleName, () => mock),
1767 setSystemTime: now => {
1768 const fakeTimers = _getFakeTimers();
1769
1770 if (fakeTimers instanceof _fakeTimers().ModernFakeTimers) {
1771 fakeTimers.setSystemTime(now);
1772 } else {
1773 throw new TypeError(
1774 'setSystemTime is not available when not using modern timers'
1775 );
1776 }
1777 },
1778 setTimeout,
1779 spyOn,
1780 unmock,
1781 useFakeTimers,
1782 useRealTimers
1783 };
1784 return jestObject;
1785 }
1786
1787 _logFormattedReferenceError(errorMessage) {
1788 const originalStack = new ReferenceError(errorMessage).stack
1789 .split('\n') // Remove this file from the stack (jest-message-utils will keep one line)
1790 .filter(line => line.indexOf(__filename) === -1)
1791 .join('\n');
1792 const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)(
1793 originalStack
1794 );
1795 console.error(
1796 `\n${message}\n` +
1797 (0, _jestMessageUtil().formatStackTrace)(stack, this._config, {
1798 noStackTrace: false
1799 })
1800 );
1801 }
1802
1803 wrapCodeInModuleWrapper(content) {
1804 return this.constructModuleWrapperStart() + content + '\n}});';
1805 }
1806
1807 constructModuleWrapperStart() {
1808 const args = this.constructInjectedModuleParameters();
1809 return '({"' + EVAL_RESULT_VARIABLE + `":function(${args.join(',')}){`;
1810 }
1811
1812 constructInjectedModuleParameters() {
1813 return [
1814 'module',
1815 'exports',
1816 'require',
1817 '__dirname',
1818 '__filename',
1819 'global',
1820 this._config.injectGlobals ? 'jest' : undefined,
1821 ...this._config.extraGlobals
1822 ].filter(notEmpty);
1823 }
1824
1825 handleExecutionError(e, module) {
1826 const moduleNotFoundError = _jestResolve().default.tryCastModuleNotFoundError(
1827 e
1828 );
1829
1830 if (moduleNotFoundError) {
1831 if (!moduleNotFoundError.requireStack) {
1832 moduleNotFoundError.requireStack = [module.filename || module.id];
1833
1834 for (let cursor = module.parent; cursor; cursor = cursor.parent) {
1835 moduleNotFoundError.requireStack.push(cursor.filename || cursor.id);
1836 }
1837
1838 moduleNotFoundError.buildMessage(this._config.rootDir);
1839 }
1840
1841 throw moduleNotFoundError;
1842 }
1843
1844 throw e;
1845 }
1846
1847 getGlobalsForCjs(from) {
1848 const jest = this.jestObjectCaches.get(from);
1849 invariant(jest, 'There should always be a Jest object already');
1850 return {...this.getGlobalsFromEnvironment(), jest};
1851 }
1852
1853 async getGlobalsForEsm(from, context) {
1854 let jest = this.jestObjectCaches.get(from);
1855
1856 if (!jest) {
1857 jest = this._createJestObjectFor(from);
1858 this.jestObjectCaches.set(from, jest);
1859 }
1860
1861 const globals = {...this.getGlobalsFromEnvironment(), jest};
1862 const module = new (_vm().SyntheticModule)(
1863 Object.keys(globals),
1864 function () {
1865 Object.entries(globals).forEach(([key, value]) => {
1866 // @ts-expect-error: TS doesn't know what `this` is
1867 this.setExport(key, value);
1868 });
1869 },
1870 {
1871 context,
1872 identifier: '@jest/globals'
1873 }
1874 );
1875 await module.link(() => {
1876 throw new Error('This should never happen');
1877 });
1878 await module.evaluate();
1879 return module;
1880 }
1881
1882 getGlobalsFromEnvironment() {
1883 if (this.jestGlobals) {
1884 return {...this.jestGlobals};
1885 }
1886
1887 return {
1888 afterAll: this._environment.global.afterAll,
1889 afterEach: this._environment.global.afterEach,
1890 beforeAll: this._environment.global.beforeAll,
1891 beforeEach: this._environment.global.beforeEach,
1892 describe: this._environment.global.describe,
1893 expect: this._environment.global.expect,
1894 fdescribe: this._environment.global.fdescribe,
1895 fit: this._environment.global.fit,
1896 it: this._environment.global.it,
1897 test: this._environment.global.test,
1898 xdescribe: this._environment.global.xdescribe,
1899 xit: this._environment.global.xit,
1900 xtest: this._environment.global.xtest
1901 };
1902 }
1903
1904 readFile(filename) {
1905 let source = this._cacheFS.get(filename);
1906
1907 if (!source) {
1908 source = fs().readFileSync(filename, 'utf8');
1909
1910 this._cacheFS.set(filename, source);
1911 }
1912
1913 return source;
1914 }
1915
1916 setGlobalsForRuntime(globals) {
1917 this.jestGlobals = globals;
1918 }
1919}
1920
1921_defineProperty(Runtime, 'shouldInstrument', _transform().shouldInstrument);
1922
1923function invariant(condition, message) {
1924 if (!condition) {
1925 throw new Error(message);
1926 }
1927}
1928
1929function notEmpty(value) {
1930 return value !== null && value !== undefined;
1931}
1932
1933module.exports = Runtime;