legacyFakeTimers.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function _util() {
  7. const data = _interopRequireDefault(require('util'));
  8. _util = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _jestMessageUtil() {
  14. const data = require('jest-message-util');
  15. _jestMessageUtil = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _jestUtil() {
  21. const data = require('jest-util');
  22. _jestUtil = function () {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function _interopRequireDefault(obj) {
  28. return obj && obj.__esModule ? obj : {default: obj};
  29. }
  30. function _defineProperty(obj, key, value) {
  31. if (key in obj) {
  32. Object.defineProperty(obj, key, {
  33. value: value,
  34. enumerable: true,
  35. configurable: true,
  36. writable: true
  37. });
  38. } else {
  39. obj[key] = value;
  40. }
  41. return obj;
  42. }
  43. const MS_IN_A_YEAR = 31536000000;
  44. class FakeTimers {
  45. constructor({global, moduleMocker, timerConfig, config, maxLoops}) {
  46. _defineProperty(this, '_cancelledTicks', void 0);
  47. _defineProperty(this, '_config', void 0);
  48. _defineProperty(this, '_disposed', void 0);
  49. _defineProperty(this, '_fakeTimerAPIs', void 0);
  50. _defineProperty(this, '_global', void 0);
  51. _defineProperty(this, '_immediates', void 0);
  52. _defineProperty(this, '_maxLoops', void 0);
  53. _defineProperty(this, '_moduleMocker', void 0);
  54. _defineProperty(this, '_now', void 0);
  55. _defineProperty(this, '_ticks', void 0);
  56. _defineProperty(this, '_timerAPIs', void 0);
  57. _defineProperty(this, '_timers', void 0);
  58. _defineProperty(this, '_uuidCounter', void 0);
  59. _defineProperty(this, '_timerConfig', void 0);
  60. this._global = global;
  61. this._timerConfig = timerConfig;
  62. this._config = config;
  63. this._maxLoops = maxLoops || 100000;
  64. this._uuidCounter = 1;
  65. this._moduleMocker = moduleMocker; // Store original timer APIs for future reference
  66. this._timerAPIs = {
  67. cancelAnimationFrame: global.cancelAnimationFrame,
  68. clearImmediate: global.clearImmediate,
  69. clearInterval: global.clearInterval,
  70. clearTimeout: global.clearTimeout,
  71. nextTick: global.process && global.process.nextTick,
  72. requestAnimationFrame: global.requestAnimationFrame,
  73. setImmediate: global.setImmediate,
  74. setInterval: global.setInterval,
  75. setTimeout: global.setTimeout
  76. };
  77. this.reset();
  78. }
  79. clearAllTimers() {
  80. this._immediates = [];
  81. this._timers.clear();
  82. }
  83. dispose() {
  84. this._disposed = true;
  85. this.clearAllTimers();
  86. }
  87. reset() {
  88. this._cancelledTicks = {};
  89. this._now = 0;
  90. this._ticks = [];
  91. this._immediates = [];
  92. this._timers = new Map();
  93. }
  94. runAllTicks() {
  95. this._checkFakeTimers(); // Only run a generous number of ticks and then bail.
  96. // This is just to help avoid recursive loops
  97. let i;
  98. for (i = 0; i < this._maxLoops; i++) {
  99. const tick = this._ticks.shift();
  100. if (tick === undefined) {
  101. break;
  102. }
  103. if (!this._cancelledTicks.hasOwnProperty(tick.uuid)) {
  104. // Callback may throw, so update the map prior calling.
  105. this._cancelledTicks[tick.uuid] = true;
  106. tick.callback();
  107. }
  108. }
  109. if (i === this._maxLoops) {
  110. throw new Error(
  111. 'Ran ' +
  112. this._maxLoops +
  113. ' ticks, and there are still more! ' +
  114. "Assuming we've hit an infinite recursion and bailing out..."
  115. );
  116. }
  117. }
  118. runAllImmediates() {
  119. this._checkFakeTimers(); // Only run a generous number of immediates and then bail.
  120. let i;
  121. for (i = 0; i < this._maxLoops; i++) {
  122. const immediate = this._immediates.shift();
  123. if (immediate === undefined) {
  124. break;
  125. }
  126. this._runImmediate(immediate);
  127. }
  128. if (i === this._maxLoops) {
  129. throw new Error(
  130. 'Ran ' +
  131. this._maxLoops +
  132. ' immediates, and there are still more! Assuming ' +
  133. "we've hit an infinite recursion and bailing out..."
  134. );
  135. }
  136. }
  137. _runImmediate(immediate) {
  138. try {
  139. immediate.callback();
  140. } finally {
  141. this._fakeClearImmediate(immediate.uuid);
  142. }
  143. }
  144. runAllTimers() {
  145. this._checkFakeTimers();
  146. this.runAllTicks();
  147. this.runAllImmediates(); // Only run a generous number of timers and then bail.
  148. // This is just to help avoid recursive loops
  149. let i;
  150. for (i = 0; i < this._maxLoops; i++) {
  151. const nextTimerHandle = this._getNextTimerHandle(); // If there are no more timer handles, stop!
  152. if (nextTimerHandle === null) {
  153. break;
  154. }
  155. this._runTimerHandle(nextTimerHandle); // Some of the immediate calls could be enqueued
  156. // during the previous handling of the timers, we should
  157. // run them as well.
  158. if (this._immediates.length) {
  159. this.runAllImmediates();
  160. }
  161. if (this._ticks.length) {
  162. this.runAllTicks();
  163. }
  164. }
  165. if (i === this._maxLoops) {
  166. throw new Error(
  167. 'Ran ' +
  168. this._maxLoops +
  169. ' timers, and there are still more! ' +
  170. "Assuming we've hit an infinite recursion and bailing out..."
  171. );
  172. }
  173. }
  174. runOnlyPendingTimers() {
  175. // We need to hold the current shape of `this._timers` because existing
  176. // timers can add new ones to the map and hence would run more than necessary.
  177. // See https://github.com/facebook/jest/pull/4608 for details
  178. const timerEntries = Array.from(this._timers.entries());
  179. this._checkFakeTimers();
  180. this._immediates.forEach(this._runImmediate, this);
  181. timerEntries
  182. .sort(([, left], [, right]) => left.expiry - right.expiry)
  183. .forEach(([timerHandle]) => this._runTimerHandle(timerHandle));
  184. }
  185. advanceTimersToNextTimer(steps = 1) {
  186. if (steps < 1) {
  187. return;
  188. }
  189. const nextExpiry = Array.from(this._timers.values()).reduce(
  190. (minExpiry, timer) => {
  191. if (minExpiry === null || timer.expiry < minExpiry) return timer.expiry;
  192. return minExpiry;
  193. },
  194. null
  195. );
  196. if (nextExpiry !== null) {
  197. this.advanceTimersByTime(nextExpiry - this._now);
  198. this.advanceTimersToNextTimer(steps - 1);
  199. }
  200. }
  201. advanceTimersByTime(msToRun) {
  202. this._checkFakeTimers(); // Only run a generous number of timers and then bail.
  203. // This is just to help avoid recursive loops
  204. let i;
  205. for (i = 0; i < this._maxLoops; i++) {
  206. const timerHandle = this._getNextTimerHandle(); // If there are no more timer handles, stop!
  207. if (timerHandle === null) {
  208. break;
  209. }
  210. const timerValue = this._timers.get(timerHandle);
  211. if (timerValue === undefined) {
  212. break;
  213. }
  214. const nextTimerExpiry = timerValue.expiry;
  215. if (this._now + msToRun < nextTimerExpiry) {
  216. // There are no timers between now and the target we're running to, so
  217. // adjust our time cursor and quit
  218. this._now += msToRun;
  219. break;
  220. } else {
  221. msToRun -= nextTimerExpiry - this._now;
  222. this._now = nextTimerExpiry;
  223. this._runTimerHandle(timerHandle);
  224. }
  225. }
  226. if (i === this._maxLoops) {
  227. throw new Error(
  228. 'Ran ' +
  229. this._maxLoops +
  230. ' timers, and there are still more! ' +
  231. "Assuming we've hit an infinite recursion and bailing out..."
  232. );
  233. }
  234. }
  235. runWithRealTimers(cb) {
  236. const prevClearImmediate = this._global.clearImmediate;
  237. const prevClearInterval = this._global.clearInterval;
  238. const prevClearTimeout = this._global.clearTimeout;
  239. const prevNextTick = this._global.process.nextTick;
  240. const prevSetImmediate = this._global.setImmediate;
  241. const prevSetInterval = this._global.setInterval;
  242. const prevSetTimeout = this._global.setTimeout;
  243. this.useRealTimers();
  244. let cbErr = null;
  245. let errThrown = false;
  246. try {
  247. cb();
  248. } catch (e) {
  249. errThrown = true;
  250. cbErr = e;
  251. }
  252. this._global.clearImmediate = prevClearImmediate;
  253. this._global.clearInterval = prevClearInterval;
  254. this._global.clearTimeout = prevClearTimeout;
  255. this._global.process.nextTick = prevNextTick;
  256. this._global.setImmediate = prevSetImmediate;
  257. this._global.setInterval = prevSetInterval;
  258. this._global.setTimeout = prevSetTimeout;
  259. if (errThrown) {
  260. throw cbErr;
  261. }
  262. }
  263. useRealTimers() {
  264. const global = this._global;
  265. if (typeof global.cancelAnimationFrame === 'function') {
  266. (0, _jestUtil().setGlobal)(
  267. global,
  268. 'cancelAnimationFrame',
  269. this._timerAPIs.cancelAnimationFrame
  270. );
  271. }
  272. if (typeof global.clearImmediate === 'function') {
  273. (0, _jestUtil().setGlobal)(
  274. global,
  275. 'clearImmediate',
  276. this._timerAPIs.clearImmediate
  277. );
  278. }
  279. (0, _jestUtil().setGlobal)(
  280. global,
  281. 'clearInterval',
  282. this._timerAPIs.clearInterval
  283. );
  284. (0, _jestUtil().setGlobal)(
  285. global,
  286. 'clearTimeout',
  287. this._timerAPIs.clearTimeout
  288. );
  289. if (typeof global.requestAnimationFrame === 'function') {
  290. (0, _jestUtil().setGlobal)(
  291. global,
  292. 'requestAnimationFrame',
  293. this._timerAPIs.requestAnimationFrame
  294. );
  295. }
  296. if (typeof global.setImmediate === 'function') {
  297. (0, _jestUtil().setGlobal)(
  298. global,
  299. 'setImmediate',
  300. this._timerAPIs.setImmediate
  301. );
  302. }
  303. (0, _jestUtil().setGlobal)(
  304. global,
  305. 'setInterval',
  306. this._timerAPIs.setInterval
  307. );
  308. (0, _jestUtil().setGlobal)(
  309. global,
  310. 'setTimeout',
  311. this._timerAPIs.setTimeout
  312. );
  313. global.process.nextTick = this._timerAPIs.nextTick;
  314. }
  315. useFakeTimers() {
  316. this._createMocks();
  317. const global = this._global;
  318. if (typeof global.cancelAnimationFrame === 'function') {
  319. (0, _jestUtil().setGlobal)(
  320. global,
  321. 'cancelAnimationFrame',
  322. this._fakeTimerAPIs.cancelAnimationFrame
  323. );
  324. }
  325. if (typeof global.clearImmediate === 'function') {
  326. (0, _jestUtil().setGlobal)(
  327. global,
  328. 'clearImmediate',
  329. this._fakeTimerAPIs.clearImmediate
  330. );
  331. }
  332. (0, _jestUtil().setGlobal)(
  333. global,
  334. 'clearInterval',
  335. this._fakeTimerAPIs.clearInterval
  336. );
  337. (0, _jestUtil().setGlobal)(
  338. global,
  339. 'clearTimeout',
  340. this._fakeTimerAPIs.clearTimeout
  341. );
  342. if (typeof global.requestAnimationFrame === 'function') {
  343. (0, _jestUtil().setGlobal)(
  344. global,
  345. 'requestAnimationFrame',
  346. this._fakeTimerAPIs.requestAnimationFrame
  347. );
  348. }
  349. if (typeof global.setImmediate === 'function') {
  350. (0, _jestUtil().setGlobal)(
  351. global,
  352. 'setImmediate',
  353. this._fakeTimerAPIs.setImmediate
  354. );
  355. }
  356. (0, _jestUtil().setGlobal)(
  357. global,
  358. 'setInterval',
  359. this._fakeTimerAPIs.setInterval
  360. );
  361. (0, _jestUtil().setGlobal)(
  362. global,
  363. 'setTimeout',
  364. this._fakeTimerAPIs.setTimeout
  365. );
  366. global.process.nextTick = this._fakeTimerAPIs.nextTick;
  367. }
  368. getTimerCount() {
  369. this._checkFakeTimers();
  370. return this._timers.size + this._immediates.length + this._ticks.length;
  371. }
  372. _checkFakeTimers() {
  373. var _this$_fakeTimerAPIs;
  374. if (
  375. this._global.setTimeout !==
  376. ((_this$_fakeTimerAPIs = this._fakeTimerAPIs) === null ||
  377. _this$_fakeTimerAPIs === void 0
  378. ? void 0
  379. : _this$_fakeTimerAPIs.setTimeout)
  380. ) {
  381. this._global.console.warn(
  382. 'A function to advance timers was called but the timers API is not ' +
  383. 'mocked with fake timers. Call `jest.useFakeTimers()` in this ' +
  384. 'test or enable fake timers globally by setting ' +
  385. '`"timers": "fake"` in ' +
  386. 'the configuration file. This warning is likely a result of a ' +
  387. 'default configuration change in Jest 15.\n\n' +
  388. 'Release Blog Post: https://jestjs.io/blog/2016/09/01/jest-15\n' +
  389. 'Stack Trace:\n' +
  390. (0, _jestMessageUtil().formatStackTrace)(
  391. new Error().stack,
  392. this._config,
  393. {
  394. noStackTrace: false
  395. }
  396. )
  397. );
  398. }
  399. }
  400. _createMocks() {
  401. const fn = (
  402. impl // @ts-expect-error TODO: figure out better typings here
  403. ) => this._moduleMocker.fn().mockImplementation(impl);
  404. const promisifiableFakeSetTimeout = fn(this._fakeSetTimeout.bind(this)); // @ts-expect-error TODO: figure out better typings here
  405. promisifiableFakeSetTimeout[_util().default.promisify.custom] = (
  406. delay,
  407. arg
  408. ) =>
  409. new Promise(resolve => promisifiableFakeSetTimeout(resolve, delay, arg)); // TODO: add better typings; these are mocks, but typed as regular timers
  410. this._fakeTimerAPIs = {
  411. cancelAnimationFrame: fn(this._fakeClearTimer.bind(this)),
  412. clearImmediate: fn(this._fakeClearImmediate.bind(this)),
  413. clearInterval: fn(this._fakeClearTimer.bind(this)),
  414. clearTimeout: fn(this._fakeClearTimer.bind(this)),
  415. nextTick: fn(this._fakeNextTick.bind(this)),
  416. // @ts-expect-error TODO: figure out better typings here
  417. requestAnimationFrame: fn(this._fakeRequestAnimationFrame.bind(this)),
  418. // @ts-expect-error TODO: figure out better typings here
  419. setImmediate: fn(this._fakeSetImmediate.bind(this)),
  420. // @ts-expect-error TODO: figure out better typings here
  421. setInterval: fn(this._fakeSetInterval.bind(this)),
  422. // @ts-expect-error TODO: figure out better typings here
  423. setTimeout: promisifiableFakeSetTimeout
  424. };
  425. }
  426. _fakeClearTimer(timerRef) {
  427. const uuid = this._timerConfig.refToId(timerRef);
  428. if (uuid) {
  429. this._timers.delete(String(uuid));
  430. }
  431. }
  432. _fakeClearImmediate(uuid) {
  433. this._immediates = this._immediates.filter(
  434. immediate => immediate.uuid !== uuid
  435. );
  436. }
  437. _fakeNextTick(callback, ...args) {
  438. if (this._disposed) {
  439. return;
  440. }
  441. const uuid = String(this._uuidCounter++);
  442. this._ticks.push({
  443. callback: () => callback.apply(null, args),
  444. uuid
  445. });
  446. const cancelledTicks = this._cancelledTicks;
  447. this._timerAPIs.nextTick(() => {
  448. if (!cancelledTicks.hasOwnProperty(uuid)) {
  449. // Callback may throw, so update the map prior calling.
  450. cancelledTicks[uuid] = true;
  451. callback.apply(null, args);
  452. }
  453. });
  454. }
  455. _fakeRequestAnimationFrame(callback) {
  456. return this._fakeSetTimeout(() => {
  457. // TODO: Use performance.now() once it's mocked
  458. callback(this._now);
  459. }, 1000 / 60);
  460. }
  461. _fakeSetImmediate(callback, ...args) {
  462. if (this._disposed) {
  463. return null;
  464. }
  465. const uuid = String(this._uuidCounter++);
  466. this._immediates.push({
  467. callback: () => callback.apply(null, args),
  468. uuid
  469. });
  470. this._timerAPIs.setImmediate(() => {
  471. if (this._immediates.find(x => x.uuid === uuid)) {
  472. try {
  473. callback.apply(null, args);
  474. } finally {
  475. this._fakeClearImmediate(uuid);
  476. }
  477. }
  478. });
  479. return uuid;
  480. }
  481. _fakeSetInterval(callback, intervalDelay, ...args) {
  482. if (this._disposed) {
  483. return null;
  484. }
  485. if (intervalDelay == null) {
  486. intervalDelay = 0;
  487. }
  488. const uuid = this._uuidCounter++;
  489. this._timers.set(String(uuid), {
  490. callback: () => callback.apply(null, args),
  491. expiry: this._now + intervalDelay,
  492. interval: intervalDelay,
  493. type: 'interval'
  494. });
  495. return this._timerConfig.idToRef(uuid);
  496. }
  497. _fakeSetTimeout(callback, delay, ...args) {
  498. if (this._disposed) {
  499. return null;
  500. } // eslint-disable-next-line no-bitwise
  501. delay = Number(delay) | 0;
  502. const uuid = this._uuidCounter++;
  503. this._timers.set(String(uuid), {
  504. callback: () => callback.apply(null, args),
  505. expiry: this._now + delay,
  506. interval: undefined,
  507. type: 'timeout'
  508. });
  509. return this._timerConfig.idToRef(uuid);
  510. }
  511. _getNextTimerHandle() {
  512. let nextTimerHandle = null;
  513. let soonestTime = MS_IN_A_YEAR;
  514. this._timers.forEach((timer, uuid) => {
  515. if (timer.expiry < soonestTime) {
  516. soonestTime = timer.expiry;
  517. nextTimerHandle = uuid;
  518. }
  519. });
  520. return nextTimerHandle;
  521. }
  522. _runTimerHandle(timerHandle) {
  523. const timer = this._timers.get(timerHandle);
  524. if (!timer) {
  525. return;
  526. }
  527. switch (timer.type) {
  528. case 'timeout':
  529. this._timers.delete(timerHandle);
  530. timer.callback();
  531. break;
  532. case 'interval':
  533. timer.expiry = this._now + (timer.interval || 0);
  534. timer.callback();
  535. break;
  536. default:
  537. throw new Error('Unexpected timer type: ' + timer.type);
  538. }
  539. }
  540. }
  541. exports.default = FakeTimers;