Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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