index.js 54 KB

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