0
# Test Runner
1
2
Jest's test runner provides both programmatic and CLI-based test execution with comprehensive configuration options, result aggregation, and performance optimization through parallel execution.
3
4
## Capabilities
5
6
### Programmatic Test Execution
7
8
Run Jest tests programmatically with full control over configuration and execution parameters.
9
10
```typescript { .api }
11
/**
12
* Runs Jest CLI programmatically with specified configuration and projects
13
* @param argv - Command line arguments and configuration
14
* @param projects - Array of project paths to run tests on
15
* @returns Promise resolving to test results and global configuration
16
*/
17
function runCLI(
18
argv: Config.Argv,
19
projects: Array<string>
20
): Promise<{
21
results: AggregatedResult;
22
globalConfig: Config.GlobalConfig;
23
}>;
24
25
interface AggregatedResult {
26
numTotalTests: number;
27
numPassedTests: number;
28
numFailedTests: number;
29
numPendingTests: number;
30
numRuntimeErrorTestSuites: number;
31
numTotalTestSuites: number;
32
numPassedTestSuites: number;
33
numFailedTestSuites: number;
34
numPendingTestSuites: number;
35
openHandles: Array<Error>;
36
snapshot: SnapshotSummary;
37
success: boolean;
38
startTime: number;
39
testResults: Array<TestResult>;
40
wasInterrupted: boolean;
41
}
42
```
43
44
**Usage Examples:**
45
46
```typescript
47
import { runCLI, buildArgv } from "jest";
48
49
// Basic test run
50
async function runTests() {
51
const argv = await buildArgv(["--testMatch=**/*.test.js"]);
52
const { results, globalConfig } = await runCLI(argv, ["./src"]);
53
54
console.log(`${results.numPassedTests}/${results.numTotalTests} tests passed`);
55
56
if (!results.success) {
57
console.error("Tests failed!");
58
process.exit(1);
59
}
60
}
61
62
// Run with coverage and JSON output
63
async function runTestsWithCoverage() {
64
const argv = await buildArgv([
65
"--coverage",
66
"--json",
67
"--outputFile=test-results.json"
68
]);
69
70
const { results } = await runCLI(argv, [process.cwd()]);
71
return results;
72
}
73
74
// Run specific test files
75
async function runSpecificTests(testFiles: string[]) {
76
const argv = await buildArgv([
77
"--runTestsByPath",
78
...testFiles
79
]);
80
81
const { results } = await runCLI(argv, [process.cwd()]);
82
return results;
83
}
84
```
85
86
### CLI Entry Point
87
88
Main CLI runner that handles argument parsing and delegates to the programmatic API.
89
90
```typescript { .api }
91
/**
92
* Main CLI entry point for Jest
93
* @param maybeArgv - Optional command line arguments (defaults to process.argv.slice(2))
94
* @param project - Optional project path
95
* @returns Promise that resolves when Jest execution completes
96
*/
97
function run(maybeArgv?: Array<string>, project?: string): Promise<void>;
98
```
99
100
**Usage Example:**
101
102
```typescript
103
import { run } from "jest";
104
105
// Run Jest with default arguments
106
await run();
107
108
// Run Jest with custom arguments
109
await run(["--watch", "--testPathPatterns=src/components"]);
110
111
// Run Jest for specific project
112
await run(["--coverage"], "./my-project");
113
```
114
115
### Argument Parsing and Validation
116
117
Parse and validate command line arguments for Jest execution.
118
119
```typescript { .api }
120
/**
121
* Builds and validates command line arguments for Jest
122
* @param maybeArgv - Optional command line arguments
123
* @returns Promise resolving to parsed and validated arguments
124
*/
125
function buildArgv(maybeArgv?: Array<string>): Promise<Config.Argv>;
126
127
interface Config.Argv {
128
// Test execution options
129
all?: boolean;
130
bail?: boolean | number;
131
findRelatedTests?: boolean;
132
listTests?: boolean;
133
onlyChanged?: boolean;
134
onlyFailures?: boolean;
135
passWithNoTests?: boolean;
136
runInBand?: boolean;
137
runTestsByPath?: boolean;
138
testNamePattern?: string;
139
testPathPatterns?: Array<string>;
140
testTimeout?: number;
141
142
// Watch mode options
143
watch?: boolean;
144
watchAll?: boolean;
145
watchPathIgnorePatterns?: Array<string>;
146
147
// Coverage options
148
collectCoverage?: boolean;
149
coverage?: boolean;
150
collectCoverageFrom?: Array<string>;
151
coverageDirectory?: string;
152
coveragePathIgnorePatterns?: Array<string>;
153
coverageProvider?: "babel" | "v8";
154
coverageReporters?: Array<string>;
155
coverageThreshold?: Record<string, number>;
156
157
// Output options
158
json?: boolean;
159
outputFile?: string;
160
verbose?: boolean;
161
silent?: boolean;
162
noStackTrace?: boolean;
163
color?: boolean;
164
colors?: boolean;
165
166
// Configuration options
167
config?: string;
168
rootDir?: string;
169
roots?: Array<string>;
170
projects?: Array<string>;
171
maxWorkers?: number | string;
172
cache?: boolean;
173
clearCache?: boolean;
174
debug?: boolean;
175
updateSnapshot?: boolean;
176
}
177
```
178
179
### Integration Patterns
180
181
Common patterns for integrating Jest into build tools and custom workflows:
182
183
**Build Tool Integration:**
184
185
```typescript
186
import { runCLI, buildArgv } from "jest";
187
188
async function buildToolIntegration(options: {
189
testFiles?: string[];
190
coverage?: boolean;
191
watch?: boolean;
192
}) {
193
const args = [];
194
195
if (options.coverage) args.push("--coverage");
196
if (options.watch) args.push("--watch");
197
if (options.testFiles) {
198
args.push("--runTestsByPath", ...options.testFiles);
199
}
200
201
const argv = await buildArgv(args);
202
const { results } = await runCLI(argv, [process.cwd()]);
203
204
return {
205
success: results.success,
206
testCount: results.numTotalTests,
207
passedTests: results.numPassedTests,
208
failedTests: results.numFailedTests,
209
coverageMap: results.coverageMap
210
};
211
}
212
```
213
214
**CI/CD Integration:**
215
216
```typescript
217
import { runCLI, buildArgv } from "jest";
218
219
async function runTestsInCI() {
220
const argv = await buildArgv([
221
"--ci",
222
"--coverage",
223
"--json",
224
"--outputFile=test-results.json",
225
"--coverageReporters=text-lcov",
226
"--coverageDirectory=coverage"
227
]);
228
229
try {
230
const { results, globalConfig } = await runCLI(argv, [process.cwd()]);
231
232
// Log summary
233
console.log(`Tests: ${results.numPassedTests}/${results.numTotalTests} passed`);
234
console.log(`Test Suites: ${results.numPassedTestSuites}/${results.numTotalTestSuites} passed`);
235
236
if (!results.success) {
237
console.error("❌ Tests failed");
238
process.exit(1);
239
}
240
241
console.log("✅ All tests passed");
242
} catch (error) {
243
console.error("Error running tests:", error);
244
process.exit(1);
245
}
246
}
247
```
248
249
**Custom Test Discovery:**
250
251
```typescript
252
import { runCLI, buildArgv } from "jest";
253
import * as fs from "fs";
254
import * as path from "path";
255
256
async function runTestsForChangedFiles(changedFiles: string[]) {
257
// Find test files related to changed source files
258
const testFiles = changedFiles
259
.filter(file => file.endsWith('.js') || file.endsWith('.ts'))
260
.map(file => {
261
const testFile = file.replace(/\.(js|ts)$/, '.test.$1');
262
return fs.existsSync(testFile) ? testFile : null;
263
})
264
.filter(Boolean) as string[];
265
266
if (testFiles.length === 0) {
267
console.log("No test files found for changed files");
268
return;
269
}
270
271
const argv = await buildArgv([
272
"--runTestsByPath",
273
...testFiles
274
]);
275
276
const { results } = await runCLI(argv, [process.cwd()]);
277
return results;
278
}
279
```