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