Jest Environment Base Class and Types for creating custom test execution environments
npx @tessl/cli install tessl/npm-jest--environment@30.1.00
# Jest Environment
1
2
Jest Environment provides the base class and TypeScript type definitions for Jest test environments. It defines the foundation for all Jest test execution environments (Node.js, JSDOM, etc.), establishing the interface for setting up isolated execution contexts for tests.
3
4
## Package Information
5
6
- **Package Name**: @jest/environment
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @jest/environment`
10
11
## Core Imports
12
13
```typescript
14
import {
15
JestEnvironment,
16
EnvironmentContext,
17
JestEnvironmentConfig,
18
ModuleWrapper,
19
Jest
20
} from "@jest/environment";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const {
27
JestEnvironment,
28
EnvironmentContext,
29
JestEnvironmentConfig,
30
ModuleWrapper,
31
Jest
32
} = require("@jest/environment");
33
```
34
35
## Basic Usage
36
37
```typescript
38
import {
39
JestEnvironment,
40
EnvironmentContext,
41
JestEnvironmentConfig
42
} from "@jest/environment";
43
import { LegacyFakeTimers, ModernFakeTimers } from "@jest/fake-timers";
44
import { ModuleMocker } from "jest-mock";
45
46
// Custom environment implementation
47
class MyCustomEnvironment extends JestEnvironment {
48
constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
49
super(config, context);
50
// Initialize custom global object
51
this.global = {} as any;
52
this.fakeTimers = null;
53
this.fakeTimersModern = null;
54
this.moduleMocker = null;
55
}
56
57
async setup(): Promise<void> {
58
// Setup environment before tests run
59
this.global.myCustomGlobal = "test value";
60
}
61
62
async teardown(): Promise<void> {
63
// Cleanup after tests complete
64
this.global = null as any;
65
}
66
67
getVmContext() {
68
// Return VM context for code execution
69
return null;
70
}
71
}
72
```
73
74
## Architecture
75
76
Jest Environment is built around several key components:
77
78
- **Base Environment Class**: Abstract `JestEnvironment` class that defines the interface
79
- **Configuration System**: `JestEnvironmentConfig` and `EnvironmentContext` for initialization
80
- **Module System Integration**: `ModuleWrapper` type for Node.js module wrapping
81
- **Jest Global Interface**: Complete `Jest` interface definition for test environments
82
- **Timer Integration**: Support for both legacy and modern fake timers
83
- **Module Mocking**: Integration with Jest's module mocking system
84
85
## Capabilities
86
87
### Environment Base Class
88
89
The core abstract class that all Jest environments must implement.
90
91
```typescript { .api }
92
/**
93
* Abstract base class for Jest test environments
94
* @template Timer - Type for timer implementation (default: unknown)
95
*/
96
declare class JestEnvironment<Timer = unknown> {
97
constructor(config: JestEnvironmentConfig, context: EnvironmentContext);
98
99
/** Global object for the test environment */
100
global: Global.Global;
101
102
/** Legacy fake timers implementation */
103
fakeTimers: LegacyFakeTimers<Timer> | null;
104
105
/** Modern fake timers implementation */
106
fakeTimersModern: ModernFakeTimers | null;
107
108
/** Module mocking utility */
109
moduleMocker: ModuleMocker | null;
110
111
/** Get VM context for code execution */
112
getVmContext(): Context | null;
113
114
/** Setup the environment before test execution */
115
setup(): Promise<void>;
116
117
/** Cleanup the environment after test execution */
118
teardown(): Promise<void>;
119
120
/** Optional test event handler */
121
handleTestEvent?: Circus.EventHandler;
122
123
/** Optional export conditions provider */
124
exportConditions?: () => Array<string>;
125
}
126
```
127
128
### Environment Configuration
129
130
Configuration types for initializing Jest environments.
131
132
```typescript { .api }
133
/**
134
* Configuration object passed to Jest environments
135
*/
136
interface JestEnvironmentConfig {
137
/** Project-specific Jest configuration */
138
projectConfig: Config.ProjectConfig;
139
/** Global Jest configuration */
140
globalConfig: Config.GlobalConfig;
141
}
142
143
/**
144
* Configuration context passed to environment constructors
145
*/
146
interface EnvironmentContext {
147
/** Console instance for the test environment */
148
console: Console;
149
/** Document block pragmas from test files */
150
docblockPragmas: Record<string, string | Array<string>>;
151
/** Path to the test file being executed */
152
testPath: string;
153
}
154
```
155
156
### Module System Integration
157
158
Types for integrating with Node.js module system during test execution.
159
160
```typescript { .api }
161
/**
162
* Function signature for wrapping Node.js modules during test execution
163
*/
164
type ModuleWrapper = (
165
this: Module['exports'],
166
module: Module,
167
exports: Module['exports'],
168
require: Module['require'],
169
__dirname: string,
170
__filename: Module['filename'],
171
jest?: Jest,
172
...sandboxInjectedGlobals: Array<Global.Global[keyof Global.Global]>
173
) => unknown;
174
175
/**
176
* Extended ImportMeta interface with Jest global for ESM modules
177
*/
178
interface JestImportMeta extends ImportMeta {
179
jest: Jest;
180
}
181
182
/**
183
* Alias for Node.js NodeModule type
184
*/
185
type Module = NodeModule;
186
```
187
188
### Jest Global Interface
189
190
Complete Jest global API interface providing all Jest methods and utilities.
191
192
```typescript { .api }
193
/**
194
* Complete Jest global API interface
195
*/
196
interface Jest {
197
// Timer Control Methods
198
/** Advance timers by milliseconds */
199
advanceTimersByTime(msToRun: number): void;
200
/** Async timer advancement */
201
advanceTimersByTimeAsync(msToRun: number): Promise<void>;
202
/** Advance to next animation frame */
203
advanceTimersToNextFrame(): void;
204
/** Advance to next timer */
205
advanceTimersToNextTimer(steps?: number): void;
206
/** Async advance to next timer */
207
advanceTimersToNextTimerAsync(steps?: number): Promise<void>;
208
/** Clear all pending timers */
209
clearAllTimers(): void;
210
/** Get count of pending timers */
211
getTimerCount(): number;
212
/** Get real system time when mocking time */
213
getRealSystemTime(): number;
214
/** Get current fake timer time */
215
now(): number;
216
/** Execute all pending timers */
217
runAllTimers(): void;
218
/** Async execute all pending timers */
219
runAllTimersAsync(): Promise<void>;
220
/** Execute only currently pending timers */
221
runOnlyPendingTimers(): void;
222
/** Async execute only pending timers */
223
runOnlyPendingTimersAsync(): Promise<void>;
224
/** Execute all setImmediate callbacks (legacy only) */
225
runAllImmediates(): void;
226
/** Execute all process.nextTick callbacks */
227
runAllTicks(): void;
228
/** Set fake system time */
229
setSystemTime(now?: number | Date): void;
230
/** Enable fake timers */
231
useFakeTimers(fakeTimersConfig?: Config.FakeTimersConfig | Config.LegacyFakeTimersConfig): Jest;
232
/** Disable fake timers */
233
useRealTimers(): Jest;
234
235
// Mock Control Methods
236
/** Disable automatic mocking */
237
autoMockOff(): Jest;
238
/** Enable automatic mocking */
239
autoMockOn(): Jest;
240
/** Clear all mock calls/results */
241
clearAllMocks(): Jest;
242
/** Reset all mocks */
243
resetAllMocks(): Jest;
244
/** Restore all mocks to original implementations */
245
restoreAllMocks(): Jest;
246
/** Disable automatic mocking */
247
disableAutomock(): Jest;
248
/** Enable automatic mocking */
249
enableAutomock(): Jest;
250
251
// Module Mocking Methods
252
/** Mock a module */
253
mock<T = unknown>(moduleName: string, moduleFactory?: () => T, options?: {virtual?: boolean}): Jest;
254
/** Unmock a module */
255
unmock(moduleName: string): Jest;
256
/** Mock without hoisting */
257
doMock<T = unknown>(moduleName: string, moduleFactory?: () => T, options?: {virtual?: boolean}): Jest;
258
/** Don't mock without hoisting */
259
dontMock(moduleName: string): Jest;
260
/** Unmock module and dependencies */
261
deepUnmock(moduleName: string): Jest;
262
/** Mock ES module */
263
unstable_mockModule<T = unknown>(moduleName: string, moduleFactory: () => T | Promise<T>, options?: {virtual?: boolean}): Jest;
264
/** Unmock ES module */
265
unstable_unmockModule(moduleName: string): Jest;
266
/** Set mock implementation */
267
setMock(moduleName: string, moduleExports: unknown): Jest;
268
/** Require actual module */
269
requireActual<T = unknown>(moduleName: string): T;
270
/** Require mocked module */
271
requireMock<T = unknown>(moduleName: string): T;
272
/** Create mock from module */
273
createMockFromModule<T = unknown>(moduleName: string): Mocked<T>;
274
/** Register mock generation callback */
275
onGenerateMock<T>(cb: (modulePath: string, moduleMock: T) => T): Jest;
276
277
// Module System Methods
278
/** Reset module registry */
279
resetModules(): Jest;
280
/** Execute function with isolated modules */
281
isolateModules(fn: () => void): Jest;
282
/** Async isolate modules */
283
isolateModulesAsync(fn: () => Promise<void>): Promise<void>;
284
285
// Mock Function Methods
286
/** Create mock function */
287
fn: ModuleMocker['fn'];
288
/** Check if function is mocked */
289
isMockFunction: ModuleMocker['isMockFunction'];
290
/** Create spy on object method */
291
spyOn: ModuleMocker['spyOn'];
292
/** Type-safe mock wrapping */
293
mocked: ModuleMocker['mocked'];
294
/** Replace object property */
295
replaceProperty: ModuleMocker['replaceProperty'];
296
297
// Test Control Methods
298
/** Set test timeout */
299
setTimeout(timeout: number): Jest;
300
/** Set test retry behavior */
301
retryTimes(
302
numRetries: number,
303
options?: {
304
logErrorsBeforeRetry?: boolean;
305
retryImmediately?: boolean;
306
waitBeforeRetry?: number;
307
}
308
): Jest;
309
310
// Utility Methods
311
/** Get random seed value */
312
getSeed(): number;
313
/** Check if environment is torn down */
314
isEnvironmentTornDown(): boolean;
315
}
316
```
317
318
## Types
319
320
```typescript { .api }
321
// Re-exported from dependencies
322
import type { Context } from 'vm';
323
import type { LegacyFakeTimers, ModernFakeTimers } from '@jest/fake-timers';
324
import type { Circus, Config, Global } from '@jest/types';
325
import type { Mocked, ModuleMocker } from 'jest-mock';
326
```