index.js 29 KB

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