index.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. 'use strict';
  2. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /**
  3. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. *
  9. */
  10. var _path;
  11. function _load_path() {
  12. return _path = _interopRequireDefault(require('path'));
  13. }
  14. var _jestHasteMap;
  15. function _load_jestHasteMap() {
  16. return _jestHasteMap = _interopRequireDefault(require('jest-haste-map'));
  17. }
  18. var _jestResolve;
  19. function _load_jestResolve() {
  20. return _jestResolve = _interopRequireDefault(require('jest-resolve'));
  21. }
  22. var _jestUtil;
  23. function _load_jestUtil() {
  24. return _jestUtil = require('jest-util');
  25. }
  26. var _jestRegexUtil;
  27. function _load_jestRegexUtil() {
  28. return _jestRegexUtil = require('jest-regex-util');
  29. }
  30. var _gracefulFs;
  31. function _load_gracefulFs() {
  32. return _gracefulFs = _interopRequireDefault(require('graceful-fs'));
  33. }
  34. var _stripBom;
  35. function _load_stripBom() {
  36. return _stripBom = _interopRequireDefault(require('strip-bom'));
  37. }
  38. var _script_transformer;
  39. function _load_script_transformer() {
  40. return _script_transformer = _interopRequireDefault(require('./script_transformer'));
  41. }
  42. var _should_instrument;
  43. function _load_should_instrument() {
  44. return _should_instrument = _interopRequireDefault(require('./should_instrument'));
  45. }
  46. var _cli;
  47. function _load_cli() {
  48. return _cli = require('./cli');
  49. }
  50. var _args;
  51. function _load_args() {
  52. return _args = require('./cli/args');
  53. }
  54. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  55. const NODE_MODULES = (_path || _load_path()).default.sep + 'node_modules' + (_path || _load_path()).default.sep;
  56. const SNAPSHOT_EXTENSION = 'snap';
  57. const getModuleNameMapper = config => {
  58. if (Array.isArray(config.moduleNameMapper) && config.moduleNameMapper.length) {
  59. return config.moduleNameMapper.map((_ref) => {
  60. var _ref2 = _slicedToArray(_ref, 2);
  61. let regex = _ref2[0],
  62. moduleName = _ref2[1];
  63. return { moduleName, regex: new RegExp(regex) };
  64. });
  65. }
  66. return null;
  67. };
  68. const unmockRegExpCache = new WeakMap();
  69. class Runtime {
  70. constructor(config, environment, resolver, cacheFS, coverageOptions) {
  71. this._cacheFS = cacheFS || Object.create(null);
  72. this._config = config;
  73. this._coverageOptions = coverageOptions || {
  74. collectCoverage: false,
  75. collectCoverageFrom: [],
  76. collectCoverageOnlyFrom: null
  77. };
  78. this._currentlyExecutingModulePath = '';
  79. this._environment = environment;
  80. this._explicitShouldMock = Object.create(null);
  81. this._internalModuleRegistry = Object.create(null);
  82. this._isCurrentlyExecutingManualMock = null;
  83. this._mockFactories = Object.create(null);
  84. this._mockRegistry = Object.create(null);
  85. this._moduleMocker = this._environment.moduleMocker;
  86. this._moduleRegistry = Object.create(null);
  87. this._needsCoverageMapped = new Set();
  88. this._resolver = resolver;
  89. this._scriptTransformer = new (_script_transformer || _load_script_transformer()).default(config);
  90. this._shouldAutoMock = config.automock;
  91. this._sourceMapRegistry = Object.create(null);
  92. this._virtualMocks = Object.create(null);
  93. this._mockMetaDataCache = Object.create(null);
  94. this._shouldMockModuleCache = Object.create(null);
  95. this._shouldUnmockTransitiveDependenciesCache = Object.create(null);
  96. this._transitiveShouldMock = Object.create(null);
  97. this._unmockList = unmockRegExpCache.get(config);
  98. if (!this._unmockList && config.unmockedModulePathPatterns) {
  99. this._unmockList = new RegExp(config.unmockedModulePathPatterns.join('|'));
  100. unmockRegExpCache.set(config, this._unmockList);
  101. }
  102. if (config.automock) {
  103. config.setupFiles.forEach(filePath => {
  104. if (filePath && filePath.includes(NODE_MODULES)) {
  105. const moduleID = this._resolver.getModuleID(this._virtualMocks, filePath);
  106. this._transitiveShouldMock[moduleID] = false;
  107. }
  108. });
  109. }
  110. this.resetModules();
  111. if (config.setupFiles.length) {
  112. for (let i = 0; i < config.setupFiles.length; i++) {
  113. this.requireModule(config.setupFiles[i]);
  114. }
  115. }
  116. }
  117. static shouldInstrument(filename, options, config) {
  118. return (0, (_should_instrument || _load_should_instrument()).default)(filename, {
  119. collectCoverage: options.collectCoverage,
  120. collectCoverageFrom: options.collectCoverageFrom,
  121. collectCoverageOnlyFrom: options.collectCoverageOnlyFrom
  122. }, config);
  123. }
  124. static createContext(config, options) {
  125. (0, (_jestUtil || _load_jestUtil()).createDirectory)(config.cacheDirectory);
  126. const instance = Runtime.createHasteMap(config, {
  127. console: options.console,
  128. maxWorkers: options.maxWorkers,
  129. resetCache: !config.cache,
  130. watch: options.watch,
  131. watchman: options.watchman
  132. });
  133. return instance.build().then(hasteMap => ({
  134. config,
  135. hasteFS: hasteMap.hasteFS,
  136. moduleMap: hasteMap.moduleMap,
  137. resolver: Runtime.createResolver(config, hasteMap.moduleMap)
  138. }), error => {
  139. throw error;
  140. });
  141. }
  142. static createHasteMap(config, options) {
  143. const ignorePattern = new RegExp([config.cacheDirectory].concat(config.modulePathIgnorePatterns).join('|'));
  144. return new (_jestHasteMap || _load_jestHasteMap()).default({
  145. cacheDirectory: config.cacheDirectory,
  146. console: options && options.console,
  147. extensions: [SNAPSHOT_EXTENSION].concat(config.moduleFileExtensions),
  148. hasteImplModulePath: config.haste.hasteImplModulePath,
  149. ignorePattern,
  150. maxWorkers: options && options.maxWorkers || 1,
  151. mocksPattern: (0, (_jestRegexUtil || _load_jestRegexUtil()).escapePathForRegex)((_path || _load_path()).default.sep + '__mocks__' + (_path || _load_path()).default.sep),
  152. name: config.name,
  153. platforms: config.haste.platforms || ['ios', 'android'],
  154. providesModuleNodeModules: config.haste.providesModuleNodeModules,
  155. resetCache: options && options.resetCache,
  156. retainAllFiles: false,
  157. roots: config.roots,
  158. useWatchman: options && options.watchman,
  159. watch: options && options.watch
  160. });
  161. }
  162. static createResolver(config, moduleMap) {
  163. return new (_jestResolve || _load_jestResolve()).default(moduleMap, {
  164. browser: config.browser,
  165. defaultPlatform: config.haste.defaultPlatform,
  166. extensions: config.moduleFileExtensions.map(extension => '.' + extension),
  167. hasCoreModules: true,
  168. moduleDirectories: config.moduleDirectories,
  169. moduleNameMapper: getModuleNameMapper(config),
  170. modulePaths: config.modulePaths,
  171. platforms: config.haste.platforms,
  172. resolver: config.resolver,
  173. rootDir: config.rootDir
  174. });
  175. }
  176. static runCLI(args, info) {
  177. return (0, (_cli || _load_cli()).run)(args, info);
  178. }
  179. static getCLIOptions() {
  180. return (_args || _load_args()).options;
  181. }
  182. requireModule(from, moduleName, options) {
  183. const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
  184. let modulePath;
  185. const moduleRegistry = !options || !options.isInternalModule ? this._moduleRegistry : this._internalModuleRegistry;
  186. // Some old tests rely on this mocking behavior. Ideally we'll change this
  187. // to be more explicit.
  188. const moduleResource = moduleName && this._resolver.getModule(moduleName);
  189. const manualMock = moduleName && this._resolver.getMockModule(from, moduleName);
  190. if ((!options || !options.isInternalModule) && !moduleResource && manualMock && manualMock !== this._isCurrentlyExecutingManualMock && this._explicitShouldMock[moduleID] !== false) {
  191. modulePath = manualMock;
  192. }
  193. if (moduleName && this._resolver.isCoreModule(moduleName)) {
  194. return this._requireCoreModule(moduleName);
  195. }
  196. if (!modulePath) {
  197. modulePath = this._resolveModule(from, moduleName);
  198. }
  199. if (!moduleRegistry[modulePath]) {
  200. // We must register the pre-allocated module object first so that any
  201. // circular dependencies that may arise while evaluating the module can
  202. const localModule = {
  203. children: [],
  204. exports: {},
  205. filename: modulePath,
  206. id: modulePath,
  207. loaded: false
  208. };
  209. moduleRegistry[modulePath] = localModule;
  210. if ((_path || _load_path()).default.extname(modulePath) === '.json') {
  211. localModule.exports = this._environment.global.JSON.parse((0, (_stripBom || _load_stripBom()).default)((_gracefulFs || _load_gracefulFs()).default.readFileSync(modulePath, 'utf8')));
  212. } else if ((_path || _load_path()).default.extname(modulePath) === '.node') {
  213. // $FlowFixMe
  214. localModule.exports = require(modulePath);
  215. } else {
  216. this._execModule(localModule, options, moduleRegistry, from);
  217. }
  218. localModule.loaded = true;
  219. }
  220. return moduleRegistry[modulePath].exports;
  221. }
  222. requireInternalModule(from, to) {
  223. return this.requireModule(from, to, { isInternalModule: true });
  224. }
  225. requireMock(from, moduleName) {
  226. const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
  227. if (this._mockRegistry[moduleID]) {
  228. return this._mockRegistry[moduleID];
  229. }
  230. if (moduleID in this._mockFactories) {
  231. return this._mockRegistry[moduleID] = this._mockFactories[moduleID]();
  232. }
  233. let manualMock = this._resolver.getMockModule(from, moduleName);
  234. let modulePath;
  235. if (manualMock) {
  236. modulePath = this._resolveModule(from, manualMock);
  237. } else {
  238. modulePath = this._resolveModule(from, moduleName);
  239. }
  240. // If the actual module file has a __mocks__ dir sitting immediately next
  241. // to it, look to see if there is a manual mock for this file.
  242. //
  243. // subDir1/my_module.js
  244. // subDir1/__mocks__/my_module.js
  245. // subDir2/my_module.js
  246. // subDir2/__mocks__/my_module.js
  247. //
  248. // Where some other module does a relative require into each of the
  249. // respective subDir{1,2} directories and expects a manual mock
  250. // corresponding to that particular my_module.js file.
  251. const moduleDir = (_path || _load_path()).default.dirname(modulePath);
  252. const moduleFileName = (_path || _load_path()).default.basename(modulePath);
  253. const potentialManualMock = (_path || _load_path()).default.join(moduleDir, '__mocks__', moduleFileName);
  254. if ((_gracefulFs || _load_gracefulFs()).default.existsSync(potentialManualMock)) {
  255. manualMock = true;
  256. modulePath = potentialManualMock;
  257. }
  258. if (manualMock) {
  259. const localModule = {
  260. children: [],
  261. exports: {},
  262. filename: modulePath,
  263. id: modulePath,
  264. loaded: false
  265. };
  266. this._execModule(localModule, undefined, this._mockRegistry, from);
  267. this._mockRegistry[moduleID] = localModule.exports;
  268. localModule.loaded = true;
  269. } else {
  270. // Look for a real module to generate an automock from
  271. this._mockRegistry[moduleID] = this._generateMock(from, moduleName);
  272. }
  273. return this._mockRegistry[moduleID];
  274. }
  275. requireModuleOrMock(from, moduleName) {
  276. if (this._shouldMock(from, moduleName)) {
  277. return this.requireMock(from, moduleName);
  278. } else {
  279. return this.requireModule(from, moduleName);
  280. }
  281. }
  282. resetModules() {
  283. this._mockRegistry = Object.create(null);
  284. this._moduleRegistry = Object.create(null);
  285. if (this._environment && this._environment.global) {
  286. const envGlobal = this._environment.global;
  287. Object.keys(envGlobal).forEach(key => {
  288. const globalMock = envGlobal[key];
  289. if (typeof globalMock === 'object' && globalMock !== null || typeof globalMock === 'function') {
  290. globalMock._isMockFunction && globalMock.mockClear();
  291. }
  292. });
  293. if (envGlobal.mockClearTimers) {
  294. envGlobal.mockClearTimers();
  295. }
  296. }
  297. }
  298. getAllCoverageInfoCopy() {
  299. return (0, (_jestUtil || _load_jestUtil()).deepCyclicCopy)(this._environment.global.__coverage__);
  300. }
  301. getSourceMapInfo(coveredFiles) {
  302. return Object.keys(this._sourceMapRegistry).reduce((result, sourcePath) => {
  303. if (coveredFiles.has(sourcePath) && this._needsCoverageMapped.has(sourcePath) && (_gracefulFs || _load_gracefulFs()).default.existsSync(this._sourceMapRegistry[sourcePath])) {
  304. result[sourcePath] = this._sourceMapRegistry[sourcePath];
  305. }
  306. return result;
  307. }, {});
  308. }
  309. getSourceMaps() {
  310. return this._sourceMapRegistry;
  311. }
  312. setMock(from, moduleName, mockFactory, options) {
  313. if (options && options.virtual) {
  314. const mockPath = this._resolver.getModulePath(from, moduleName);
  315. this._virtualMocks[mockPath] = true;
  316. }
  317. const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
  318. this._explicitShouldMock[moduleID] = true;
  319. this._mockFactories[moduleID] = mockFactory;
  320. }
  321. restoreAllMocks() {
  322. this._moduleMocker.restoreAllMocks();
  323. }
  324. resetAllMocks() {
  325. this._moduleMocker.resetAllMocks();
  326. }
  327. clearAllMocks() {
  328. this._moduleMocker.clearAllMocks();
  329. }
  330. _resolveModule(from, to) {
  331. return to ? this._resolver.resolveModule(from, to) : from;
  332. }
  333. _execModule(localModule, options, moduleRegistry, from) {
  334. // If the environment was disposed, prevent this module from being executed.
  335. if (!this._environment.global) {
  336. return;
  337. }
  338. const isInternalModule = !!(options && options.isInternalModule);
  339. const filename = localModule.filename;
  340. const lastExecutingModulePath = this._currentlyExecutingModulePath;
  341. this._currentlyExecutingModulePath = filename;
  342. const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock;
  343. this._isCurrentlyExecutingManualMock = filename;
  344. const dirname = (_path || _load_path()).default.dirname(filename);
  345. localModule.children = [];
  346. Object.defineProperty(localModule, 'parent',
  347. // https://github.com/facebook/flow/issues/285#issuecomment-270810619
  348. {
  349. enumerable: true,
  350. get() {
  351. return moduleRegistry[from] || null;
  352. }
  353. });
  354. localModule.paths = this._resolver.getModulePaths(dirname);
  355. Object.defineProperty(localModule, 'require', {
  356. value: this._createRequireImplementation(localModule, options)
  357. });
  358. const transformedFile = this._scriptTransformer.transform(filename, {
  359. collectCoverage: this._coverageOptions.collectCoverage,
  360. collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
  361. collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
  362. isInternalModule
  363. }, this._cacheFS[filename]);
  364. if (transformedFile.sourceMapPath) {
  365. this._sourceMapRegistry[filename] = transformedFile.sourceMapPath;
  366. if (transformedFile.mapCoverage) {
  367. this._needsCoverageMapped.add(filename);
  368. }
  369. }
  370. const wrapper = this._environment.runScript(transformedFile.script)[(_script_transformer || _load_script_transformer()).default.EVAL_RESULT_VARIABLE];
  371. wrapper.call(localModule.exports, // module context
  372. localModule, // module object
  373. localModule.exports, // module exports
  374. localModule.require, // require implementation
  375. dirname, // __dirname
  376. filename, // __filename
  377. this._environment.global, // global object
  378. this._createJestObjectFor(filename,
  379. // $FlowFixMe
  380. localModule.require) // jest object
  381. );
  382. this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
  383. this._currentlyExecutingModulePath = lastExecutingModulePath;
  384. }
  385. _requireCoreModule(moduleName) {
  386. if (moduleName === 'process') {
  387. return this._environment.global.process;
  388. }
  389. // $FlowFixMe
  390. return require(moduleName);
  391. }
  392. _generateMock(from, moduleName) {
  393. const modulePath = this._resolveModule(from, moduleName);
  394. if (!(modulePath in this._mockMetaDataCache)) {
  395. // This allows us to handle circular dependencies while generating an
  396. // automock
  397. this._mockMetaDataCache[modulePath] = this._moduleMocker.getMetadata({});
  398. // In order to avoid it being possible for automocking to potentially
  399. // cause side-effects within the module environment, we need to execute
  400. // the module in isolation. This could cause issues if the module being
  401. // mocked has calls into side-effectful APIs on another module.
  402. const origMockRegistry = this._mockRegistry;
  403. const origModuleRegistry = this._moduleRegistry;
  404. this._mockRegistry = Object.create(null);
  405. this._moduleRegistry = Object.create(null);
  406. const moduleExports = this.requireModule(from, moduleName);
  407. // Restore the "real" module/mock registries
  408. this._mockRegistry = origMockRegistry;
  409. this._moduleRegistry = origModuleRegistry;
  410. const mockMetadata = this._moduleMocker.getMetadata(moduleExports);
  411. if (mockMetadata == null) {
  412. throw new Error(`Failed to get mock metadata: ${modulePath}\n\n` + `See: http://facebook.github.io/jest/docs/manual-mocks.html#content`);
  413. }
  414. this._mockMetaDataCache[modulePath] = mockMetadata;
  415. }
  416. return this._moduleMocker.generateFromMetadata(this._mockMetaDataCache[modulePath]);
  417. }
  418. _shouldMock(from, moduleName) {
  419. const mockPath = this._resolver.getModulePath(from, moduleName);
  420. if (mockPath in this._virtualMocks) {
  421. return true;
  422. }
  423. const explicitShouldMock = this._explicitShouldMock;
  424. const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
  425. const key = from + (_path || _load_path()).default.delimiter + moduleID;
  426. if (moduleID in explicitShouldMock) {
  427. return explicitShouldMock[moduleID];
  428. }
  429. if (!this._shouldAutoMock || this._resolver.isCoreModule(moduleName) || this._shouldUnmockTransitiveDependenciesCache[key]) {
  430. return false;
  431. }
  432. if (moduleID in this._shouldMockModuleCache) {
  433. return this._shouldMockModuleCache[moduleID];
  434. }
  435. let modulePath;
  436. try {
  437. modulePath = this._resolveModule(from, moduleName);
  438. } catch (e) {
  439. const manualMock = this._resolver.getMockModule(from, moduleName);
  440. if (manualMock) {
  441. this._shouldMockModuleCache[moduleID] = true;
  442. return true;
  443. }
  444. throw e;
  445. }
  446. if (this._unmockList && this._unmockList.test(modulePath)) {
  447. this._shouldMockModuleCache[moduleID] = false;
  448. return false;
  449. }
  450. // transitive unmocking for package managers that store flat packages (npm3)
  451. const currentModuleID = this._resolver.getModuleID(this._virtualMocks, from);
  452. if (this._transitiveShouldMock[currentModuleID] === false || from.includes(NODE_MODULES) && modulePath.includes(NODE_MODULES) && (this._unmockList && this._unmockList.test(from) || explicitShouldMock[currentModuleID] === false)) {
  453. this._transitiveShouldMock[moduleID] = false;
  454. this._shouldUnmockTransitiveDependenciesCache[key] = true;
  455. return false;
  456. }
  457. return this._shouldMockModuleCache[moduleID] = true;
  458. }
  459. _createRequireImplementation(from, options) {
  460. const moduleRequire = options && options.isInternalModule ? moduleName => this.requireInternalModule(from.filename, moduleName) : this.requireModuleOrMock.bind(this, from.filename);
  461. moduleRequire.cache = Object.create(null);
  462. moduleRequire.extensions = Object.create(null);
  463. moduleRequire.requireActual = this.requireModule.bind(this, from.filename);
  464. moduleRequire.requireMock = this.requireMock.bind(this, from.filename);
  465. moduleRequire.resolve = moduleName => this._resolveModule(from.filename, moduleName);
  466. Object.defineProperty(moduleRequire, 'main', {
  467. enumerable: true,
  468. get() {
  469. let mainModule = from.parent;
  470. while (mainModule && mainModule.parent && mainModule.id !== mainModule.parent.id) {
  471. mainModule = mainModule.parent;
  472. }
  473. return mainModule;
  474. }
  475. });
  476. return moduleRequire;
  477. }
  478. _createJestObjectFor(from, localRequire) {
  479. const disableAutomock = () => {
  480. this._shouldAutoMock = false;
  481. return jestObject;
  482. };
  483. const enableAutomock = () => {
  484. this._shouldAutoMock = true;
  485. return jestObject;
  486. };
  487. const unmock = moduleName => {
  488. const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
  489. this._explicitShouldMock[moduleID] = false;
  490. return jestObject;
  491. };
  492. const deepUnmock = moduleName => {
  493. const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
  494. this._explicitShouldMock[moduleID] = false;
  495. this._transitiveShouldMock[moduleID] = false;
  496. return jestObject;
  497. };
  498. const mock = (moduleName, mockFactory, options) => {
  499. if (mockFactory !== undefined) {
  500. return setMockFactory(moduleName, mockFactory, options);
  501. }
  502. const moduleID = this._resolver.getModuleID(this._virtualMocks, from, moduleName);
  503. this._explicitShouldMock[moduleID] = true;
  504. return jestObject;
  505. };
  506. const setMockFactory = (moduleName, mockFactory, options) => {
  507. this.setMock(from, moduleName, mockFactory, options);
  508. return jestObject;
  509. };
  510. const clearAllMocks = () => {
  511. this.clearAllMocks();
  512. return jestObject;
  513. };
  514. const resetAllMocks = () => {
  515. this.resetAllMocks();
  516. return jestObject;
  517. };
  518. const restoreAllMocks = () => {
  519. this.restoreAllMocks();
  520. return jestObject;
  521. };
  522. const useFakeTimers = () => {
  523. this._environment.fakeTimers.useFakeTimers();
  524. return jestObject;
  525. };
  526. const useRealTimers = () => {
  527. this._environment.fakeTimers.useRealTimers();
  528. return jestObject;
  529. };
  530. const resetModules = () => {
  531. this.resetModules();
  532. return jestObject;
  533. };
  534. const fn = this._moduleMocker.fn.bind(this._moduleMocker);
  535. const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker);
  536. const setTimeout = timeout => {
  537. this._environment.global.jasmine ? this._environment.global.jasmine.DEFAULT_TIMEOUT_INTERVAL = timeout : this._environment.global[Symbol.for('TEST_TIMEOUT_SYMBOL')] = timeout;
  538. return jestObject;
  539. };
  540. const jestObject = {
  541. addMatchers: matchers => this._environment.global.jasmine.addMatchers(matchers),
  542. advanceTimersByTime: msToRun => this._environment.fakeTimers.advanceTimersByTime(msToRun),
  543. autoMockOff: disableAutomock,
  544. autoMockOn: enableAutomock,
  545. clearAllMocks,
  546. clearAllTimers: () => this._environment.fakeTimers.clearAllTimers(),
  547. deepUnmock,
  548. disableAutomock,
  549. doMock: mock,
  550. dontMock: unmock,
  551. enableAutomock,
  552. fn,
  553. genMockFn: fn,
  554. genMockFromModule: moduleName => this._generateMock(from, moduleName),
  555. genMockFunction: fn,
  556. isMockFunction: this._moduleMocker.isMockFunction,
  557. mock,
  558. requireActual: localRequire.requireActual,
  559. requireMock: localRequire.requireMock,
  560. resetAllMocks,
  561. resetModuleRegistry: resetModules,
  562. resetModules,
  563. restoreAllMocks,
  564. runAllImmediates: () => this._environment.fakeTimers.runAllImmediates(),
  565. runAllTicks: () => this._environment.fakeTimers.runAllTicks(),
  566. runAllTimers: () => this._environment.fakeTimers.runAllTimers(),
  567. runOnlyPendingTimers: () => this._environment.fakeTimers.runOnlyPendingTimers(),
  568. runTimersToTime: msToRun => this._environment.fakeTimers.advanceTimersByTime(msToRun),
  569. setMock: (moduleName, mock) => setMockFactory(moduleName, () => mock),
  570. setTimeout,
  571. spyOn,
  572. unmock,
  573. useFakeTimers,
  574. useRealTimers
  575. };
  576. return jestObject;
  577. }
  578. }
  579. Runtime.ScriptTransformer = (_script_transformer || _load_script_transformer()).default;
  580. module.exports = Runtime;