0
# Legacy Fake Timers
1
2
Backward-compatible fake timer implementation with custom Jest timer control and precise execution ordering. This implementation provides deterministic timer behavior for tests that require the older Jest fake timers API.
3
4
## Capabilities
5
6
### Constructor
7
8
Creates a new LegacyFakeTimers instance with the specified configuration.
9
10
```typescript { .api }
11
/**
12
* Creates a new LegacyFakeTimers instance
13
* @param options - Configuration object
14
*/
15
constructor<TimerRef = unknown>(options: {
16
global: typeof globalThis;
17
moduleMocker: ModuleMocker;
18
timerConfig: TimerConfig<TimerRef>;
19
config: StackTraceConfig;
20
maxLoops?: number;
21
}): LegacyFakeTimers<TimerRef>;
22
```
23
24
**Usage Example:**
25
26
```typescript
27
import { LegacyFakeTimers } from "@jest/fake-timers";
28
29
const fakeTimers = new LegacyFakeTimers({
30
global: globalThis,
31
moduleMocker: moduleMocker,
32
timerConfig: {
33
idToRef: (id) => id,
34
refToId: (ref) => ref
35
},
36
config: stackTraceConfig,
37
maxLoops: 100000
38
});
39
```
40
41
### Timer Control
42
43
#### Use Fake Timers
44
45
Enables fake timers by replacing all timer APIs with mock implementations.
46
47
```typescript { .api }
48
/**
49
* Enables fake timers
50
*/
51
useFakeTimers(): void;
52
```
53
54
#### Use Real Timers
55
56
Restores the original timer implementations.
57
58
```typescript { .api }
59
/**
60
* Restores original timer implementations
61
*/
62
useRealTimers(): void;
63
```
64
65
#### Run With Real Timers
66
67
Temporarily executes a callback with real timers, then restores fake timers.
68
69
```typescript { .api }
70
/**
71
* Executes callback with real timers temporarily
72
* @param cb - Callback function to execute
73
*/
74
runWithRealTimers(cb: Callback): void;
75
```
76
77
**Usage Example:**
78
79
```typescript
80
fakeTimers.runWithRealTimers(() => {
81
// This code runs with real timers
82
setTimeout(() => console.log('Real timer'), 100);
83
});
84
// Fake timers are restored after callback
85
```
86
87
### Timer Execution
88
89
#### Run All Timers
90
91
Executes all pending timers, immediates, and ticks until none remain.
92
93
```typescript { .api }
94
/**
95
* Runs all pending timers until none remain
96
*/
97
runAllTimers(): void;
98
```
99
100
**Usage Example:**
101
102
```typescript
103
setTimeout(() => console.log('Timer 1'), 100);
104
setTimeout(() => console.log('Timer 2'), 200);
105
106
fakeTimers.runAllTimers();
107
// Both timers execute in order
108
```
109
110
#### Run Only Pending Timers
111
112
Executes only the timers that are currently pending, preserving execution order.
113
114
```typescript { .api }
115
/**
116
* Runs only currently pending timers
117
*/
118
runOnlyPendingTimers(): void;
119
```
120
121
#### Run All Ticks
122
123
Executes all pending process.nextTick callbacks.
124
125
```typescript { .api }
126
/**
127
* Runs all pending process.nextTick callbacks
128
*/
129
runAllTicks(): void;
130
```
131
132
#### Run All Immediates
133
134
Executes all pending setImmediate callbacks.
135
136
```typescript { .api }
137
/**
138
* Runs all pending setImmediate callbacks
139
*/
140
runAllImmediates(): void;
141
```
142
143
### Time Advancement
144
145
#### Advance Timers by Time
146
147
Advances the fake clock by the specified number of milliseconds.
148
149
```typescript { .api }
150
/**
151
* Advances fake time by specified milliseconds
152
* @param msToRun - Number of milliseconds to advance
153
*/
154
advanceTimersByTime(msToRun: number): void;
155
```
156
157
**Usage Example:**
158
159
```typescript
160
let executed = false;
161
setTimeout(() => { executed = true; }, 1000);
162
163
fakeTimers.advanceTimersByTime(1000);
164
console.log(executed); // true
165
```
166
167
#### Advance Timers to Next Timer
168
169
Advances time to the next scheduled timer and optionally repeats.
170
171
```typescript { .api }
172
/**
173
* Advances time to the next scheduled timer
174
* @param steps - Number of timer steps to advance (default: 1)
175
*/
176
advanceTimersToNextTimer(steps?: number): void;
177
```
178
179
**Usage Example:**
180
181
```typescript
182
setTimeout(() => console.log('First'), 100);
183
setTimeout(() => console.log('Second'), 200);
184
185
fakeTimers.advanceTimersToNextTimer(1);
186
// Executes 'First', time is now at 100ms
187
188
fakeTimers.advanceTimersToNextTimer(1);
189
// Executes 'Second', time is now at 200ms
190
```
191
192
### State Management
193
194
#### Reset
195
196
Resets all timer state to initial conditions.
197
198
```typescript { .api }
199
/**
200
* Resets all timer state to initial conditions
201
*/
202
reset(): void;
203
```
204
205
#### Clear All Timers
206
207
Clears all pending timers without executing them.
208
209
```typescript { .api }
210
/**
211
* Clears all pending timers
212
*/
213
clearAllTimers(): void;
214
```
215
216
#### Now
217
218
Returns the current fake time.
219
220
```typescript { .api }
221
/**
222
* Gets current fake time in milliseconds
223
* @returns Current fake time
224
*/
225
now(): number;
226
```
227
228
#### Get Timer Count
229
230
Returns the total number of pending timers, immediates, and ticks.
231
232
```typescript { .api }
233
/**
234
* Gets the total count of pending timers
235
* @returns Number of pending timers, immediates, and ticks
236
*/
237
getTimerCount(): number;
238
```
239
240
#### Dispose
241
242
Disposes of the fake timers instance and clears all state.
243
244
```typescript { .api }
245
/**
246
* Disposes of the fake timers instance
247
*/
248
dispose(): void;
249
```
250
251
## Types
252
253
```typescript { .api }
254
type Callback = (...args: Array<unknown>) => void;
255
256
interface TimerConfig<Ref> {
257
/** Convert timer ID to reference */
258
idToRef: (id: number) => Ref;
259
/** Convert reference to timer ID */
260
refToId: (ref: Ref) => number | void;
261
}
262
263
interface ModuleMocker {
264
fn<T extends FunctionLike = UnknownFunction>(
265
implementation?: T
266
): Mock<T>;
267
}
268
269
interface StackTraceConfig {
270
rootDir: string;
271
testMatch: Array<string>;
272
}
273
```
274
275
## Error Handling
276
277
Legacy fake timers include protection against infinite recursion:
278
279
- **Maximum Loop Protection**: Prevents infinite timer loops with configurable `maxLoops` parameter (default: 100,000)
280
- **Stack Trace Integration**: Provides detailed error messages with stack traces when timer limits are exceeded
281
- **Proper Cleanup**: Ensures timers are properly disposed of to prevent memory leaks