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