jestFakeTimers.js 15 KB

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