index.js 67 KB

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