Jest's test runner responsible for orchestrating test execution, managing worker processes, and coordinating parallel test runs
npx @tessl/cli install tessl/npm-jest-runner@30.1.00
# Jest Runner
1
2
Jest Runner is the core test execution engine of the Jest testing framework, responsible for orchestrating test execution, managing worker processes, and coordinating parallel test runs. It provides both serial and parallel test execution modes, manages worker process lifecycles, and implements an event-driven architecture for real-time test progress reporting.
3
4
## Package Information
5
6
- **Package Name**: jest-runner
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install jest-runner`
10
11
## Core Imports
12
13
```typescript
14
import TestRunner from "jest-runner";
15
import {
16
CallbackTestRunner,
17
EmittingTestRunner,
18
type CallbackTestRunnerInterface,
19
type EmittingTestRunnerInterface,
20
type TestRunnerOptions,
21
type TestRunnerContext,
22
type TestFramework,
23
type ErrorWithCode,
24
type JestTestRunner,
25
type OnTestStart,
26
type OnTestFailure,
27
type OnTestSuccess,
28
type UnsubscribeFn,
29
type Test,
30
type TestEvents,
31
type Config,
32
type TestWatcher
33
} from "jest-runner";
34
```
35
36
For CommonJS:
37
38
```javascript
39
const TestRunner = require("jest-runner");
40
const {
41
CallbackTestRunner,
42
EmittingTestRunner,
43
// Types are not available in CommonJS, use JSDoc for type hints
44
} = require("jest-runner");
45
```
46
47
## Basic Usage
48
49
```typescript
50
import TestRunner from "jest-runner";
51
import { TestWatcher } from "jest-watcher";
52
import type { Test } from "@jest/test-result";
53
import type { Config } from "@jest/types";
54
55
// Create test runner instance
56
const globalConfig: Config.GlobalConfig = { /* Jest configuration */ };
57
const context = {
58
changedFiles: new Set<string>(),
59
sourcesRelatedToTestsInChangedFiles: new Set<string>()
60
};
61
const runner = new TestRunner(globalConfig, context);
62
63
// Prepare tests
64
const tests: Test[] = [
65
{
66
path: "/path/to/test1.js",
67
context: { /* test context */ }
68
}
69
];
70
71
// Set up watcher
72
const watcher = new TestWatcher({ isWatchMode: false });
73
74
// Run tests
75
await runner.runTests(tests, watcher, { serial: false });
76
77
// Listen to events
78
runner.on('test-file-start', ([test]) => {
79
console.log(`Starting test: ${test.path}`);
80
});
81
82
runner.on('test-file-success', ([test, result]) => {
83
console.log(`Test passed: ${test.path}`);
84
});
85
```
86
87
## Architecture
88
89
Jest Runner is built around several key components:
90
91
- **TestRunner Class**: The main default export implementing `EmittingTestRunner` for event-driven test execution
92
- **Abstract Base Classes**: `CallbackTestRunner` and `EmittingTestRunner` for creating custom test runners
93
- **Worker Process Management**: Parallel test execution using `jest-worker` with configurable worker limits
94
- **Event System**: Real-time progress reporting through typed event emissions
95
- **Test Execution Engine**: Core `runTest` function handling individual test file execution
96
- **Memory Management**: Leak detection and configurable memory limits for worker processes
97
98
## Capabilities
99
100
### Test Runner Implementation
101
102
The main `TestRunner` class providing both serial and parallel test execution with event-driven progress reporting.
103
104
```typescript { .api }
105
export default class TestRunner extends EmittingTestRunner {
106
constructor(globalConfig: Config.GlobalConfig, context: TestRunnerContext);
107
108
runTests(
109
tests: Array<Test>,
110
watcher: TestWatcher,
111
options: TestRunnerOptions
112
): Promise<void>;
113
114
on<Name extends keyof TestEvents>(
115
eventName: Name,
116
listener: (eventData: TestEvents[Name]) => void | Promise<void>
117
): UnsubscribeFn;
118
}
119
```
120
121
[Test Runner Implementation](./test-runner.md)
122
123
### Custom Test Runner Framework
124
125
Abstract base classes and interfaces for building custom test runners with both callback and event-driven patterns.
126
127
```typescript { .api }
128
abstract class CallbackTestRunner extends BaseTestRunner {
129
readonly supportsEventEmitters = false;
130
131
abstract runTests(
132
tests: Array<Test>,
133
watcher: TestWatcher,
134
onStart: OnTestStart,
135
onResult: OnTestSuccess,
136
onFailure: OnTestFailure,
137
options: TestRunnerOptions
138
): Promise<void>;
139
}
140
141
abstract class EmittingTestRunner extends BaseTestRunner {
142
readonly supportsEventEmitters = true;
143
144
abstract runTests(
145
tests: Array<Test>,
146
watcher: TestWatcher,
147
options: TestRunnerOptions
148
): Promise<void>;
149
150
abstract on<Name extends keyof TestEvents>(
151
eventName: Name,
152
listener: (eventData: TestEvents[Name]) => void | Promise<void>
153
): UnsubscribeFn;
154
}
155
```
156
157
[Custom Test Runner Framework](./custom-runner.md)
158
159
### Core Test Execution
160
161
Internal test execution engine used by the TestRunner class. The `runTest` function handles individual test file execution with environment setup, framework integration, and result collection.
162
163
**Note**: This is an internal API used by TestRunner and not directly exported for public use.
164
165
[Core Test Execution](./core-execution.md)
166
167
### Worker Process Management
168
169
Internal worker process management system for parallel test execution. These functions handle worker setup, test execution, and communication between main and worker processes.
170
171
**Note**: These are internal APIs used by TestRunner's parallel execution mode and not directly exported for public use.
172
173
[Worker Process Management](./worker-management.md)
174
175
## Core Types
176
177
```typescript { .api }
178
interface TestRunnerOptions {
179
serial: boolean;
180
}
181
182
interface TestRunnerContext {
183
changedFiles?: Set<string>;
184
sourcesRelatedToTestsInChangedFiles?: Set<string>;
185
}
186
187
interface TestContext {
188
config: Config.ProjectConfig;
189
moduleMap: ModuleMap;
190
resolver: Resolver;
191
}
192
193
// Re-exported from @jest/test-result
194
interface Test {
195
path: string;
196
context: TestContext;
197
}
198
199
interface TestEvents {
200
'test-file-start': [Test];
201
'test-file-success': [Test, TestResult];
202
'test-file-failure': [Test, SerializableError];
203
}
204
205
interface TestResult {
206
console: ConsoleBuffer;
207
coverage?: CoverageMap;
208
displayName?: Config.DisplayName;
209
leaks: boolean;
210
memoryUsage?: number;
211
numFailingTests: number;
212
numPassingTests: number;
213
numPendingTests: number;
214
numTodoTests: number;
215
perfStats: TestPerformanceStats;
216
skipped: boolean;
217
testFilePath: string;
218
testResults: Array<AssertionResult>;
219
v8Coverage?: V8CoverageResult[];
220
}
221
222
interface SerializableError {
223
message: string;
224
stack?: string;
225
type: string;
226
code?: string;
227
}
228
229
interface TestPerformanceStats {
230
start: number;
231
end: number;
232
runtime: number;
233
slow: boolean;
234
loadTestEnvironmentStart: number;
235
loadTestEnvironmentEnd: number;
236
setupFilesStart: number;
237
setupFilesEnd: number;
238
}
239
240
type TestFramework = (
241
globalConfig: Config.GlobalConfig,
242
config: Config.ProjectConfig,
243
environment: JestEnvironment,
244
runtime: RuntimeType,
245
testPath: string,
246
sendMessageToJest?: TestFileEvent
247
) => Promise<TestResult>;
248
249
type ErrorWithCode = Error & { code?: string };
250
251
type OnTestStart = (test: Test) => Promise<void>;
252
type OnTestFailure = (test: Test, serializableError: SerializableError) => Promise<void>;
253
type OnTestSuccess = (test: Test, testResult: TestResult) => Promise<void>;
254
type UnsubscribeFn = () => void;
255
type JestTestRunner = CallbackTestRunner | EmittingTestRunner;
256
257
type TestFileEvent = (
258
eventName: string,
259
args: Array<any>
260
) => void | Promise<void>;
261
262
interface JestEnvironment {
263
global: typeof globalThis;
264
getVmContext(): vm.Context | null;
265
setup(): Promise<void>;
266
teardown(): Promise<void>;
267
}
268
269
interface AssertionResult {
270
ancestorTitles: Array<string>;
271
duration?: number;
272
failureDetails: Array<unknown>;
273
failureMessages: Array<string>;
274
fullName: string;
275
invocations?: number;
276
location?: Callsite;
277
numPassingAsserts: number;
278
retryReasons?: Array<string>;
279
status: 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled';
280
title: string;
281
}
282
283
interface ConsoleBuffer extends Array<LogEntry> {}
284
285
interface LogEntry {
286
message: string;
287
origin: string;
288
type: LogType;
289
}
290
291
type LogType = 'assert' | 'count' | 'debug' | 'dir' | 'dirxml' | 'error' | 'group' | 'groupCollapsed' | 'groupEnd' | 'info' | 'log' | 'time' | 'warn';
292
293
interface Callsite {
294
column: number;
295
line: number;
296
}
297
298
// Re-exported types from dependencies - use these imports to access them
299
// import type { ModuleMap, Resolver, RuntimeType } from '@jest/types';
300
// import type { CoverageMap, V8CoverageResult } from 'istanbul-lib-coverage';
301
```