index.js 74 KB

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