index.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. 'use strict';
  2. function _path() {
  3. const data = _interopRequireDefault(require('path'));
  4. _path = function _path() {
  5. return data;
  6. };
  7. return data;
  8. }
  9. function _jestHasteMap() {
  10. const data = _interopRequireDefault(require('jest-haste-map'));
  11. _jestHasteMap = function _jestHasteMap() {
  12. return data;
  13. };
  14. return data;
  15. }
  16. function _jestMessageUtil() {
  17. const data = require('jest-message-util');
  18. _jestMessageUtil = function _jestMessageUtil() {
  19. return data;
  20. };
  21. return data;
  22. }
  23. function _jestResolve() {
  24. const data = _interopRequireDefault(require('jest-resolve'));
  25. _jestResolve = function _jestResolve() {
  26. return data;
  27. };
  28. return data;
  29. }
  30. function _jestUtil() {
  31. const data = require('jest-util');
  32. _jestUtil = function _jestUtil() {
  33. return data;
  34. };
  35. return data;
  36. }
  37. function _jestRegexUtil() {
  38. const data = require('jest-regex-util');
  39. _jestRegexUtil = function _jestRegexUtil() {
  40. return data;
  41. };
  42. return data;
  43. }
  44. function _jestSnapshot() {
  45. const data = _interopRequireDefault(require('jest-snapshot'));
  46. _jestSnapshot = function _jestSnapshot() {
  47. return data;
  48. };
  49. return data;
  50. }
  51. function _transform() {
  52. const data = require('@jest/transform');
  53. _transform = function _transform() {
  54. return data;
  55. };
  56. return data;
  57. }
  58. function _gracefulFs() {
  59. const data = _interopRequireDefault(require('graceful-fs'));
  60. _gracefulFs = function _gracefulFs() {
  61. return data;
  62. };
  63. return data;
  64. }
  65. function _stripBom() {
  66. const data = _interopRequireDefault(require('strip-bom'));
  67. _stripBom = function _stripBom() {
  68. return data;
  69. };
  70. return data;
  71. }
  72. var _cli = require('./cli');
  73. var _args = require('./cli/args');
  74. var _helpers = require('./helpers');
  75. function _interopRequireDefault(obj) {
  76. return obj && obj.__esModule ? obj : {default: obj};
  77. }
  78. function _objectSpread(target) {
  79. for (var i = 1; i < arguments.length; i++) {
  80. var source = arguments[i] != null ? arguments[i] : {};
  81. var ownKeys = Object.keys(source);
  82. if (typeof Object.getOwnPropertySymbols === 'function') {
  83. ownKeys = ownKeys.concat(
  84. Object.getOwnPropertySymbols(source).filter(function(sym) {
  85. return Object.getOwnPropertyDescriptor(source, sym).enumerable;
  86. })
  87. );
  88. }
  89. ownKeys.forEach(function(key) {
  90. _defineProperty(target, key, source[key]);
  91. });
  92. }
  93. return target;
  94. }
  95. function _defineProperty(obj, key, value) {
  96. if (key in obj) {
  97. Object.defineProperty(obj, key, {
  98. value: value,
  99. enumerable: true,
  100. configurable: true,
  101. writable: true
  102. });
  103. } else {
  104. obj[key] = value;
  105. }
  106. return obj;
  107. }
  108. const testTimeoutSymbol = Symbol.for('TEST_TIMEOUT_SYMBOL');
  109. const retryTimesSymbol = Symbol.for('RETRY_TIMES');
  110. const NODE_MODULES = _path().default.sep + 'node_modules' + _path().default.sep;
  111. const getModuleNameMapper = config => {
  112. if (
  113. Array.isArray(config.moduleNameMapper) &&
  114. config.moduleNameMapper.length
  115. ) {
  116. return config.moduleNameMapper.map(([regex, moduleName]) => ({
  117. moduleName,
  118. regex: new RegExp(regex)
  119. }));
  120. }
  121. return null;
  122. };
  123. const unmockRegExpCache = new WeakMap();
  124. /* eslint-disable-next-line no-redeclare */
  125. class Runtime {
  126. constructor(config, environment, resolver, cacheFS, coverageOptions) {
  127. _defineProperty(this, '_cacheFS', void 0);
  128. _defineProperty(this, '_config', void 0);
  129. _defineProperty(this, '_coverageOptions', void 0);
  130. _defineProperty(this, '_currentlyExecutingModulePath', void 0);
  131. _defineProperty(this, '_environment', void 0);
  132. _defineProperty(this, '_explicitShouldMock', void 0);
  133. _defineProperty(this, '_internalModuleRegistry', void 0);
  134. _defineProperty(this, '_isCurrentlyExecutingManualMock', void 0);
  135. _defineProperty(this, '_mockFactories', void 0);
  136. _defineProperty(this, '_mockMetaDataCache', void 0);
  137. _defineProperty(this, '_mockRegistry', void 0);
  138. _defineProperty(this, '_isolatedMockRegistry', void 0);
  139. _defineProperty(this, '_moduleMocker', void 0);
  140. _defineProperty(this, '_isolatedModuleRegistry', void 0);
  141. _defineProperty(this, '_moduleRegistry', void 0);
  142. _defineProperty(this, '_needsCoverageMapped', void 0);
  143. _defineProperty(this, '_resolver', void 0);
  144. _defineProperty(this, '_shouldAutoMock', void 0);
  145. _defineProperty(this, '_shouldMockModuleCache', void 0);
  146. _defineProperty(this, '_shouldUnmockTransitiveDependenciesCache', void 0);
  147. _defineProperty(this, '_sourceMapRegistry', void 0);
  148. _defineProperty(this, '_scriptTransformer', void 0);
  149. _defineProperty(this, '_transitiveShouldMock', void 0);
  150. _defineProperty(this, '_unmockList', void 0);
  151. _defineProperty(this, '_virtualMocks', void 0);
  152. this._cacheFS = cacheFS || Object.create(null);
  153. this._config = config;
  154. this._coverageOptions = coverageOptions || {
  155. changedFiles: undefined,
  156. collectCoverage: false,
  157. collectCoverageFrom: [],
  158. collectCoverageOnlyFrom: null
  159. };
  160. this._currentlyExecutingModulePath = '';
  161. this._environment = environment;
  162. this._explicitShouldMock = Object.create(null);
  163. this._internalModuleRegistry = new Map();
  164. this._isCurrentlyExecutingManualMock = null;
  165. this._mockFactories = Object.create(null);
  166. this._mockRegistry = new Map(); // during setup, this cannot be null (and it's fine to explode if it is)
  167. this._moduleMocker = this._environment.moduleMocker;
  168. this._isolatedModuleRegistry = null;
  169. this._isolatedMockRegistry = null;
  170. this._moduleRegistry = new Map();
  171. this._needsCoverageMapped = new Set();
  172. this._resolver = resolver;
  173. this._scriptTransformer = new (_transform()).ScriptTransformer(config);
  174. this._shouldAutoMock = config.automock;
  175. this._sourceMapRegistry = Object.create(null);
  176. this._virtualMocks = Object.create(null);
  177. this._mockMetaDataCache = Object.create(null);
  178. this._shouldMockModuleCache = Object.create(null);
  179. this._shouldUnmockTransitiveDependenciesCache = Object.create(null);
  180. this._transitiveShouldMock = Object.create(null);
  181. this._unmockList = unmockRegExpCache.get(config);
  182. if (!this._unmockList && config.unmockedModulePathPatterns) {
  183. this._unmockList = new RegExp(
  184. config.unmockedModulePathPatterns.join('|')
  185. );
  186. unmockRegExpCache.set(config, this._unmockList);
  187. }
  188. if (config.automock) {
  189. config.setupFiles.forEach(filePath => {
  190. if (filePath && filePath.includes(NODE_MODULES)) {
  191. const moduleID = this._resolver.getModuleID(
  192. this._virtualMocks,
  193. filePath
  194. );
  195. this._transitiveShouldMock[moduleID] = false;
  196. }
  197. });
  198. }
  199. this.resetModules();
  200. if (config.setupFiles.length) {
  201. for (let i = 0; i < config.setupFiles.length; i++) {
  202. this.requireModule(config.setupFiles[i]);
  203. }
  204. }
  205. } // TODO: Make this `static shouldInstrument = shouldInstrument;` after https://github.com/facebook/jest/issues/7846
  206. static shouldInstrument(filename, options, config) {
  207. return (0, _transform().shouldInstrument)(filename, options, config);
  208. }
  209. static createContext(config, options) {
  210. (0, _jestUtil().createDirectory)(config.cacheDirectory);
  211. const instance = Runtime.createHasteMap(config, {
  212. console: options.console,
  213. maxWorkers: options.maxWorkers,
  214. resetCache: !config.cache,
  215. watch: options.watch,
  216. watchman: options.watchman
  217. });
  218. return instance.build().then(
  219. hasteMap => ({
  220. config,
  221. hasteFS: hasteMap.hasteFS,
  222. moduleMap: hasteMap.moduleMap,
  223. resolver: Runtime.createResolver(config, hasteMap.moduleMap)
  224. }),
  225. error => {
  226. throw error;
  227. }
  228. );
  229. }
  230. static createHasteMap(config, options) {
  231. const ignorePatternParts = [
  232. ...config.modulePathIgnorePatterns,
  233. ...(options && options.watch ? config.watchPathIgnorePatterns : []),
  234. config.cacheDirectory.startsWith(config.rootDir + _path().default.sep) &&
  235. config.cacheDirectory
  236. ].filter(Boolean);
  237. const ignorePattern =
  238. ignorePatternParts.length > 0
  239. ? new RegExp(ignorePatternParts.join('|'))
  240. : undefined;
  241. return new (_jestHasteMap()).default({
  242. cacheDirectory: config.cacheDirectory,
  243. computeSha1: config.haste.computeSha1,
  244. console: options && options.console,
  245. dependencyExtractor: config.dependencyExtractor,
  246. extensions: [_jestSnapshot().default.EXTENSION].concat(
  247. config.moduleFileExtensions
  248. ),
  249. hasteImplModulePath: config.haste.hasteImplModulePath,
  250. ignorePattern,
  251. maxWorkers: (options && options.maxWorkers) || 1,
  252. mocksPattern: (0, _jestRegexUtil().escapePathForRegex)(
  253. _path().default.sep + '__mocks__' + _path().default.sep
  254. ),
  255. name: config.name,
  256. platforms: config.haste.platforms || ['ios', 'android'],
  257. providesModuleNodeModules: config.haste.providesModuleNodeModules,
  258. resetCache: options && options.resetCache,
  259. retainAllFiles: false,
  260. rootDir: config.rootDir,
  261. roots: config.roots,
  262. throwOnModuleCollision: config.haste.throwOnModuleCollision,
  263. useWatchman: options && options.watchman,
  264. watch: options && options.watch
  265. });
  266. }
  267. static createResolver(config, moduleMap) {
  268. return new (_jestResolve()).default(moduleMap, {
  269. browser: config.browser,
  270. defaultPlatform: config.haste.defaultPlatform,
  271. extensions: config.moduleFileExtensions.map(extension => '.' + extension),
  272. hasCoreModules: true,
  273. moduleDirectories: config.moduleDirectories,
  274. moduleNameMapper: getModuleNameMapper(config),
  275. modulePaths: config.modulePaths,
  276. platforms: config.haste.platforms,
  277. resolver: config.resolver,
  278. rootDir: config.rootDir
  279. });
  280. }
  281. static runCLI(args, info) {
  282. return (0, _cli.run)(args, info);
  283. }
  284. static getCLIOptions() {
  285. return _args.options;
  286. }
  287. requireModule(from, moduleName, options, isRequireActual) {
  288. const moduleID = this._resolver.getModuleID(
  289. this._virtualMocks,
  290. from,
  291. moduleName
  292. );
  293. let modulePath; // Some old tests rely on this mocking behavior. Ideally we'll change this
  294. // to be more explicit.
  295. const moduleResource = moduleName && this._resolver.getModule(moduleName);
  296. const manualMock =
  297. moduleName && this._resolver.getMockModule(from, moduleName);
  298. if (
  299. (!options || !options.isInternalModule) &&
  300. !isRequireActual &&
  301. !moduleResource &&
  302. manualMock &&
  303. manualMock !== this._isCurrentlyExecutingManualMock &&
  304. this._explicitShouldMock[moduleID] !== false
  305. ) {
  306. modulePath = manualMock;
  307. }
  308. if (moduleName && this._resolver.isCoreModule(moduleName)) {
  309. return this._requireCoreModule(moduleName);
  310. }
  311. if (!modulePath) {
  312. modulePath = this._resolveModule(from, moduleName);
  313. }
  314. let moduleRegistry;
  315. if (!options || !options.isInternalModule) {
  316. if (
  317. this._moduleRegistry.get(modulePath) ||
  318. !this._isolatedModuleRegistry
  319. ) {
  320. moduleRegistry = this._moduleRegistry;
  321. } else {
  322. moduleRegistry = this._isolatedModuleRegistry;
  323. }
  324. } else {
  325. moduleRegistry = this._internalModuleRegistry;
  326. }
  327. const module = moduleRegistry.get(modulePath);
  328. if (module) {
  329. return module.exports;
  330. } // We must register the pre-allocated module object first so that any
  331. // circular dependencies that may arise while evaluating the module can
  332. // be satisfied.
  333. const localModule = {
  334. children: [],
  335. exports: {},
  336. filename: modulePath,
  337. id: modulePath,
  338. loaded: false
  339. };
  340. moduleRegistry.set(modulePath, localModule);
  341. this._loadModule(
  342. localModule,
  343. from,
  344. moduleName,
  345. modulePath,
  346. options,
  347. moduleRegistry
  348. );
  349. return localModule.exports;
  350. }
  351. requireInternalModule(from, to) {
  352. return this.requireModule(from, to, {
  353. isInternalModule: true
  354. });
  355. }
  356. requireActual(from, moduleName) {
  357. return this.requireModule(from, moduleName, undefined, true);
  358. }
  359. requireMock(from, moduleName) {
  360. const moduleID = this._resolver.getModuleID(
  361. this._virtualMocks,
  362. from,
  363. moduleName
  364. );
  365. if (
  366. this._isolatedMockRegistry &&
  367. this._isolatedMockRegistry.get(moduleID)
  368. ) {
  369. return this._isolatedMockRegistry.get(moduleID);
  370. } else if (this._mockRegistry.get(moduleID)) {
  371. return this._mockRegistry.get(moduleID);
  372. }
  373. const mockRegistry = this._isolatedMockRegistry || this._mockRegistry;
  374. if (moduleID in this._mockFactories) {
  375. const module = this._mockFactories[moduleID]();
  376. mockRegistry.set(moduleID, module);
  377. return module;
  378. }
  379. const manualMockOrStub = this._resolver.getMockModule(from, moduleName);
  380. let modulePath;
  381. if (manualMockOrStub) {
  382. modulePath = this._resolveModule(from, manualMockOrStub);
  383. } else {
  384. modulePath = this._resolveModule(from, moduleName);
  385. }
  386. let isManualMock =
  387. manualMockOrStub &&
  388. !this._resolver.resolveStubModuleName(from, moduleName);
  389. if (!isManualMock) {
  390. // If the actual module file has a __mocks__ dir sitting immediately next
  391. // to it, look to see if there is a manual mock for this file.
  392. //
  393. // subDir1/my_module.js
  394. // subDir1/__mocks__/my_module.js
  395. // subDir2/my_module.js
  396. // subDir2/__mocks__/my_module.js
  397. //
  398. // Where some other module does a relative require into each of the
  399. // respective subDir{1,2} directories and expects a manual mock
  400. // corresponding to that particular my_module.js file.
  401. const moduleDir = _path().default.dirname(modulePath);
  402. const moduleFileName = _path().default.basename(modulePath);
  403. const potentialManualMock = _path().default.join(
  404. moduleDir,
  405. '__mocks__',
  406. moduleFileName
  407. );
  408. if (_gracefulFs().default.existsSync(potentialManualMock)) {
  409. isManualMock = true;
  410. modulePath = potentialManualMock;
  411. }
  412. }
  413. if (isManualMock) {
  414. const localModule = {
  415. children: [],
  416. exports: {},
  417. filename: modulePath,
  418. id: modulePath,
  419. loaded: false
  420. };
  421. this._loadModule(
  422. localModule,
  423. from,
  424. moduleName,
  425. modulePath,
  426. undefined,
  427. mockRegistry
  428. );
  429. mockRegistry.set(moduleID, localModule.exports);
  430. } else {
  431. // Look for a real module to generate an automock from
  432. mockRegistry.set(moduleID, this._generateMock(from, moduleName));
  433. }
  434. return mockRegistry.get(moduleID);
  435. }
  436. _loadModule(
  437. localModule,
  438. from,
  439. moduleName,
  440. modulePath,
  441. options,
  442. moduleRegistry
  443. ) {
  444. if (_path().default.extname(modulePath) === '.json') {
  445. const text = (0, _stripBom().default)(
  446. _gracefulFs().default.readFileSync(modulePath, 'utf8')
  447. );
  448. const transformedFile = this._scriptTransformer.transformJson(
  449. modulePath,
  450. this._getFullTransformationOptions(options),
  451. text
  452. );
  453. localModule.exports = this._environment.global.JSON.parse(
  454. transformedFile
  455. );
  456. } else if (_path().default.extname(modulePath) === '.node') {
  457. localModule.exports = require(modulePath);
  458. } else {
  459. // Only include the fromPath if a moduleName is given. Else treat as root.
  460. const fromPath = moduleName ? from : null;
  461. this._execModule(localModule, options, moduleRegistry, fromPath);
  462. }
  463. localModule.loaded = true;
  464. }
  465. _getFullTransformationOptions(options) {
  466. return _objectSpread({}, options, {
  467. changedFiles: this._coverageOptions.changedFiles,
  468. collectCoverage: this._coverageOptions.collectCoverage,
  469. collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
  470. collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
  471. extraGlobals: this._config.extraGlobals || []
  472. });
  473. }
  474. requireModuleOrMock(from, moduleName) {
  475. try {
  476. if (this._shouldMock(from, moduleName)) {
  477. return this.requireMock(from, moduleName);
  478. } else {
  479. return this.requireModule(from, moduleName);
  480. }
  481. } catch (e) {
  482. if (e.code === 'MODULE_NOT_FOUND') {
  483. const appendedMessage = (0, _helpers.findSiblingsWithFileExtension)(
  484. this._config.moduleFileExtensions,
  485. from,
  486. moduleName
  487. );
  488. if (appendedMessage) {
  489. e.message += appendedMessage;
  490. }
  491. }
  492. throw e;
  493. }
  494. }
  495. isolateModules(fn) {
  496. if (this._isolatedModuleRegistry || this._isolatedMockRegistry) {
  497. throw new Error(
  498. 'isolateModules cannot be nested inside another isolateModules.'
  499. );
  500. }
  501. this._isolatedModuleRegistry = new Map();
  502. this._isolatedMockRegistry = new Map();
  503. fn();
  504. this._isolatedModuleRegistry = null;
  505. this._isolatedMockRegistry = null;
  506. }
  507. resetModules() {
  508. this._isolatedModuleRegistry = null;
  509. this._isolatedMockRegistry = null;
  510. this._mockRegistry.clear();
  511. this._moduleRegistry.clear();
  512. if (this._environment) {
  513. if (this._environment.global) {
  514. const envGlobal = this._environment.global;
  515. Object.keys(envGlobal).forEach(key => {
  516. const globalMock = envGlobal[key];
  517. if (
  518. ((typeof globalMock === 'object' && globalMock !== null) ||
  519. typeof globalMock === 'function') &&
  520. globalMock._isMockFunction === true
  521. ) {
  522. globalMock.mockClear();
  523. }
  524. });
  525. }
  526. if (this._environment.fakeTimers) {
  527. this._environment.fakeTimers.clearAllTimers();
  528. }
  529. }
  530. }
  531. getAllCoverageInfoCopy() {
  532. return (0, _jestUtil().deepCyclicCopy)(
  533. this._environment.global.__coverage__
  534. );
  535. }
  536. getSourceMapInfo(coveredFiles) {
  537. return Object.keys(this._sourceMapRegistry).reduce((result, sourcePath) => {
  538. if (
  539. coveredFiles.has(sourcePath) &&
  540. this._needsCoverageMapped.has(sourcePath) &&
  541. _gracefulFs().default.existsSync(this._sourceMapRegistry[sourcePath])
  542. ) {
  543. result[sourcePath] = this._sourceMapRegistry[sourcePath];
  544. }
  545. return result;
  546. }, {});
  547. }
  548. getSourceMaps() {
  549. return this._sourceMapRegistry;
  550. }
  551. setMock(from, moduleName, mockFactory, options) {
  552. if (options && options.virtual) {
  553. const mockPath = this._resolver.getModulePath(from, moduleName);
  554. this._virtualMocks[mockPath] = true;
  555. }
  556. const moduleID = this._resolver.getModuleID(
  557. this._virtualMocks,
  558. from,
  559. moduleName
  560. );
  561. this._explicitShouldMock[moduleID] = true;
  562. this._mockFactories[moduleID] = mockFactory;
  563. }
  564. restoreAllMocks() {
  565. this._moduleMocker.restoreAllMocks();
  566. }
  567. resetAllMocks() {
  568. this._moduleMocker.resetAllMocks();
  569. }
  570. clearAllMocks() {
  571. this._moduleMocker.clearAllMocks();
  572. }
  573. _resolveModule(from, to) {
  574. return to ? this._resolver.resolveModule(from, to) : from;
  575. }
  576. _requireResolve(from, moduleName, options = {}) {
  577. if (moduleName == null) {
  578. throw new Error(
  579. 'The first argument to require.resolve must be a string. Received null or undefined.'
  580. );
  581. }
  582. const paths = options.paths;
  583. if (paths) {
  584. var _iteratorNormalCompletion = true;
  585. var _didIteratorError = false;
  586. var _iteratorError = undefined;
  587. try {
  588. for (
  589. var _iterator = paths[Symbol.iterator](), _step;
  590. !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
  591. _iteratorNormalCompletion = true
  592. ) {
  593. const p = _step.value;
  594. const absolutePath = _path().default.resolve(from, '..', p);
  595. const module = this._resolver.resolveModuleFromDirIfExists(
  596. absolutePath,
  597. moduleName, // required to also resolve files without leading './' directly in the path
  598. {
  599. paths: [absolutePath]
  600. }
  601. );
  602. if (module) {
  603. return module;
  604. }
  605. }
  606. } catch (err) {
  607. _didIteratorError = true;
  608. _iteratorError = err;
  609. } finally {
  610. try {
  611. if (!_iteratorNormalCompletion && _iterator.return != null) {
  612. _iterator.return();
  613. }
  614. } finally {
  615. if (_didIteratorError) {
  616. throw _iteratorError;
  617. }
  618. }
  619. }
  620. throw new Error(
  621. `Cannot resolve module '${moduleName}' from paths ['${paths.join(
  622. "', '"
  623. )}'] from ${from}`
  624. );
  625. }
  626. try {
  627. return this._resolveModule(from, moduleName);
  628. } catch (err) {
  629. const module = this._resolver.getMockModule(from, moduleName);
  630. if (module) {
  631. return module;
  632. } else {
  633. throw err;
  634. }
  635. }
  636. }
  637. _requireResolvePaths(from, moduleName) {
  638. if (moduleName == null) {
  639. throw new Error(
  640. 'The first argument to require.resolve.paths must be a string. Received null or undefined.'
  641. );
  642. }
  643. if (!moduleName.length) {
  644. throw new Error(
  645. 'The first argument to require.resolve.paths must not be the empty string.'
  646. );
  647. }
  648. if (moduleName[0] === '.') {
  649. return [_path().default.resolve(from, '..')];
  650. }
  651. if (this._resolver.isCoreModule(moduleName)) {
  652. return null;
  653. }
  654. return this._resolver.getModulePaths(_path().default.resolve(from, '..'));
  655. }
  656. _execModule(localModule, options, moduleRegistry, from) {
  657. // If the environment was disposed, prevent this module from being executed.
  658. if (!this._environment.global) {
  659. return;
  660. }
  661. const filename = localModule.filename;
  662. const lastExecutingModulePath = this._currentlyExecutingModulePath;
  663. this._currentlyExecutingModulePath = filename;
  664. const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
  665. this._isCurrentlyExecutingManualMock = filename;
  666. const dirname = _path().default.dirname(filename);
  667. localModule.children = [];
  668. Object.defineProperty(localModule, 'parent', {
  669. enumerable: true,
  670. get() {
  671. const key = from || '';
  672. return moduleRegistry.get(key) || null;
  673. }
  674. });
  675. localModule.paths = this._resolver.getModulePaths(dirname);
  676. Object.defineProperty(localModule, 'require', {
  677. value: this._createRequireImplementation(localModule, options)
  678. });
  679. const extraGlobals = this._config.extraGlobals || [];
  680. const transformedFile = this._scriptTransformer.transform(
  681. filename,
  682. this._getFullTransformationOptions(options),
  683. this._cacheFS[filename]
  684. );
  685. if (transformedFile.sourceMapPath) {
  686. this._sourceMapRegistry[filename] = transformedFile.sourceMapPath;
  687. if (transformedFile.mapCoverage) {
  688. this._needsCoverageMapped.add(filename);
  689. }
  690. }
  691. const runScript = this._environment.runScript(transformedFile.script);
  692. if (runScript === null) {
  693. this._logFormattedReferenceError(
  694. 'You are trying to `import` a file after the Jest environment has been torn down.'
  695. );
  696. process.exitCode = 1;
  697. return;
  698. } //Wrapper
  699. runScript[_transform().ScriptTransformer.EVAL_RESULT_VARIABLE].call(
  700. localModule.exports,
  701. localModule, // module object
  702. localModule.exports, // module exports
  703. localModule.require, // require implementation
  704. dirname, // __dirname
  705. filename, // __filename
  706. this._environment.global, // global object
  707. this._createJestObjectFor(filename, localModule.require), // jest object
  708. ...extraGlobals.map(globalVariable => {
  709. if (this._environment.global[globalVariable]) {
  710. return this._environment.global[globalVariable];
  711. }
  712. throw new Error(
  713. `You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`
  714. );
  715. })
  716. );
  717. this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
  718. this._currentlyExecutingModulePath = lastExecutingModulePath;
  719. }
  720. _requireCoreModule(moduleName) {
  721. if (moduleName === 'process') {
  722. return this._environment.global.process;
  723. }
  724. return require(moduleName);
  725. }
  726. _generateMock(from, moduleName) {
  727. const modulePath =
  728. this._resolver.resolveStubModuleName(from, moduleName) ||
  729. this._resolveModule(from, moduleName);
  730. if (!(modulePath in this._mockMetaDataCache)) {
  731. // This allows us to handle circular dependencies while generating an
  732. // automock
  733. this._mockMetaDataCache[modulePath] =
  734. this._moduleMocker.getMetadata({}) || {}; // In order to avoid it being possible for automocking to potentially
  735. // cause side-effects within the module environment, we need to execute
  736. // the module in isolation. This could cause issues if the module being
  737. // mocked has calls into side-effectful APIs on another module.
  738. const origMockRegistry = this._mockRegistry;
  739. const origModuleRegistry = this._moduleRegistry;
  740. this._mockRegistry = new Map();
  741. this._moduleRegistry = new Map();
  742. const moduleExports = this.requireModule(from, moduleName); // Restore the "real" module/mock registries
  743. this._mockRegistry = origMockRegistry;
  744. this._moduleRegistry = origModuleRegistry;
  745. const mockMetadata = this._moduleMocker.getMetadata(moduleExports);
  746. if (mockMetadata == null) {
  747. throw new Error(
  748. `Failed to get mock metadata: ${modulePath}\n\n` +
  749. `See: https://jestjs.io/docs/manual-mocks.html#content`
  750. );
  751. }
  752. this._mockMetaDataCache[modulePath] = mockMetadata;
  753. }
  754. return this._moduleMocker.generateFromMetadata(
  755. this._mockMetaDataCache[modulePath]
  756. );
  757. }
  758. _shouldMock(from, moduleName) {
  759. const explicitShouldMock = this._explicitShouldMock;
  760. const moduleID = this._resolver.getModuleID(
  761. this._virtualMocks,
  762. from,
  763. moduleName
  764. );
  765. const key = from + _path().default.delimiter + moduleID;
  766. if (moduleID in explicitShouldMock) {
  767. return explicitShouldMock[moduleID];
  768. }
  769. if (
  770. !this._shouldAutoMock ||
  771. this._resolver.isCoreModule(moduleName) ||
  772. this._shouldUnmockTransitiveDependenciesCache[key]
  773. ) {
  774. return false;
  775. }
  776. if (moduleID in this._shouldMockModuleCache) {
  777. return this._shouldMockModuleCache[moduleID];
  778. }
  779. let modulePath;
  780. try {
  781. modulePath = this._resolveModule(from, moduleName);
  782. } catch (e) {
  783. const manualMock = this._resolver.getMockModule(from, moduleName);
  784. if (manualMock) {
  785. this._shouldMockModuleCache[moduleID] = true;
  786. return true;
  787. }
  788. throw e;
  789. }
  790. if (this._unmockList && this._unmockList.test(modulePath)) {
  791. this._shouldMockModuleCache[moduleID] = false;
  792. return false;
  793. } // transitive unmocking for package managers that store flat packages (npm3)
  794. const currentModuleID = this._resolver.getModuleID(
  795. this._virtualMocks,
  796. from
  797. );
  798. if (
  799. this._transitiveShouldMock[currentModuleID] === false ||
  800. (from.includes(NODE_MODULES) &&
  801. modulePath.includes(NODE_MODULES) &&
  802. ((this._unmockList && this._unmockList.test(from)) ||
  803. explicitShouldMock[currentModuleID] === false))
  804. ) {
  805. this._transitiveShouldMock[moduleID] = false;
  806. this._shouldUnmockTransitiveDependenciesCache[key] = true;
  807. return false;
  808. }
  809. return (this._shouldMockModuleCache[moduleID] = true);
  810. }
  811. _createRequireImplementation(from, options) {
  812. // TODO: somehow avoid having to type the arguments - they should come from `NodeRequire/LocalModuleRequire.resolve`
  813. const resolve = (moduleName, options) =>
  814. this._requireResolve(from.filename, moduleName, options);
  815. resolve.paths = moduleName =>
  816. this._requireResolvePaths(from.filename, moduleName);
  817. const moduleRequire =
  818. options && options.isInternalModule
  819. ? moduleName => this.requireInternalModule(from.filename, moduleName)
  820. : this.requireModuleOrMock.bind(this, from.filename);
  821. moduleRequire.cache = Object.create(null);
  822. moduleRequire.extensions = Object.create(null);
  823. moduleRequire.requireActual = this.requireActual.bind(this, from.filename);
  824. moduleRequire.requireMock = this.requireMock.bind(this, from.filename);
  825. moduleRequire.resolve = resolve;
  826. Object.defineProperty(moduleRequire, 'main', {
  827. enumerable: true,
  828. get() {
  829. let mainModule = from.parent;
  830. while (
  831. mainModule &&
  832. mainModule.parent &&
  833. mainModule.id !== mainModule.parent.id
  834. ) {
  835. mainModule = mainModule.parent;
  836. }
  837. return mainModule;
  838. }
  839. });
  840. return moduleRequire;
  841. }
  842. _createJestObjectFor(from, localRequire) {
  843. const disableAutomock = () => {
  844. this._shouldAutoMock = false;
  845. return jestObject;
  846. };
  847. const enableAutomock = () => {
  848. this._shouldAutoMock = true;
  849. return jestObject;
  850. };
  851. const unmock = moduleName => {
  852. const moduleID = this._resolver.getModuleID(
  853. this._virtualMocks,
  854. from,
  855. moduleName
  856. );
  857. this._explicitShouldMock[moduleID] = false;
  858. return jestObject;
  859. };
  860. const deepUnmock = moduleName => {
  861. const moduleID = this._resolver.getModuleID(
  862. this._virtualMocks,
  863. from,
  864. moduleName
  865. );
  866. this._explicitShouldMock[moduleID] = false;
  867. this._transitiveShouldMock[moduleID] = false;
  868. return jestObject;
  869. };
  870. const mock = (moduleName, mockFactory, options) => {
  871. if (mockFactory !== undefined) {
  872. return setMockFactory(moduleName, mockFactory, options);
  873. }
  874. const moduleID = this._resolver.getModuleID(
  875. this._virtualMocks,
  876. from,
  877. moduleName
  878. );
  879. this._explicitShouldMock[moduleID] = true;
  880. return jestObject;
  881. };
  882. const setMockFactory = (moduleName, mockFactory, options) => {
  883. this.setMock(from, moduleName, mockFactory, options);
  884. return jestObject;
  885. };
  886. const clearAllMocks = () => {
  887. this.clearAllMocks();
  888. return jestObject;
  889. };
  890. const resetAllMocks = () => {
  891. this.resetAllMocks();
  892. return jestObject;
  893. };
  894. const restoreAllMocks = () => {
  895. this.restoreAllMocks();
  896. return jestObject;
  897. };
  898. const useFakeTimers = () => {
  899. _getFakeTimers().useFakeTimers();
  900. return jestObject;
  901. };
  902. const useRealTimers = () => {
  903. _getFakeTimers().useRealTimers();
  904. return jestObject;
  905. };
  906. const resetModules = () => {
  907. this.resetModules();
  908. return jestObject;
  909. };
  910. const isolateModules = fn => {
  911. this.isolateModules(fn);
  912. return jestObject;
  913. };
  914. const fn = this._moduleMocker.fn.bind(this._moduleMocker);
  915. const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker);
  916. const setTimeout = timeout => {
  917. if (this._environment.global.jasmine) {
  918. this._environment.global.jasmine._DEFAULT_TIMEOUT_INTERVAL = timeout;
  919. } else {
  920. // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/24587
  921. this._environment.global[testTimeoutSymbol] = timeout;
  922. }
  923. return jestObject;
  924. };
  925. const retryTimes = numTestRetries => {
  926. // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/24587
  927. this._environment.global[retryTimesSymbol] = numTestRetries;
  928. return jestObject;
  929. };
  930. const _getFakeTimers = () => {
  931. if (!this._environment.fakeTimers) {
  932. this._logFormattedReferenceError(
  933. 'You are trying to access a property or method of the Jest environment after it has been torn down.'
  934. );
  935. process.exitCode = 1;
  936. } // We've logged a user message above, so it doesn't matter if we return `null` here
  937. return this._environment.fakeTimers;
  938. };
  939. const jestObject = {
  940. addMatchers: matchers =>
  941. this._environment.global.jasmine.addMatchers(matchers),
  942. advanceTimersByTime: msToRun =>
  943. _getFakeTimers().advanceTimersByTime(msToRun),
  944. advanceTimersToNextTimer: steps =>
  945. _getFakeTimers().advanceTimersToNextTimer(steps),
  946. autoMockOff: disableAutomock,
  947. autoMockOn: enableAutomock,
  948. clearAllMocks,
  949. clearAllTimers: () => _getFakeTimers().clearAllTimers(),
  950. deepUnmock,
  951. disableAutomock,
  952. doMock: mock,
  953. dontMock: unmock,
  954. enableAutomock,
  955. fn,
  956. genMockFromModule: moduleName => this._generateMock(from, moduleName),
  957. getTimerCount: () => _getFakeTimers().getTimerCount(),
  958. isMockFunction: this._moduleMocker.isMockFunction,
  959. isolateModules,
  960. mock,
  961. requireActual: localRequire.requireActual,
  962. requireMock: localRequire.requireMock,
  963. resetAllMocks,
  964. resetModuleRegistry: resetModules,
  965. resetModules,
  966. restoreAllMocks,
  967. retryTimes,
  968. runAllImmediates: () => _getFakeTimers().runAllImmediates(),
  969. runAllTicks: () => _getFakeTimers().runAllTicks(),
  970. runAllTimers: () => _getFakeTimers().runAllTimers(),
  971. runOnlyPendingTimers: () => _getFakeTimers().runOnlyPendingTimers(),
  972. runTimersToTime: msToRun => _getFakeTimers().advanceTimersByTime(msToRun),
  973. setMock: (moduleName, mock) => setMockFactory(moduleName, () => mock),
  974. setTimeout,
  975. spyOn,
  976. unmock,
  977. useFakeTimers,
  978. useRealTimers
  979. };
  980. return jestObject;
  981. }
  982. _logFormattedReferenceError(errorMessage) {
  983. const originalStack = new ReferenceError(errorMessage).stack
  984. .split('\n') // Remove this file from the stack (jest-message-utils will keep one line)
  985. .filter(line => line.indexOf(__filename) === -1)
  986. .join('\n');
  987. const _separateMessageFromS = (0,
  988. _jestMessageUtil().separateMessageFromStack)(originalStack),
  989. message = _separateMessageFromS.message,
  990. stack = _separateMessageFromS.stack;
  991. console.error(
  992. `\n${message}\n` +
  993. (0, _jestMessageUtil().formatStackTrace)(stack, this._config, {
  994. noStackTrace: false
  995. })
  996. );
  997. }
  998. }
  999. _defineProperty(Runtime, 'ScriptTransformer', void 0);
  1000. Runtime.ScriptTransformer = _transform().ScriptTransformer;
  1001. module.exports = Runtime;