0
# Configuration
1
2
Jest provides a comprehensive configuration system supporting global settings, per-project configuration, and extensive customization options for all aspects of test execution.
3
4
## Capabilities
5
6
### Core Configuration Types
7
8
Jest uses a hierarchical configuration system with different types serving specific purposes.
9
10
```typescript { .api }
11
/**
12
* Main user configuration interface (alias for Config.InitialOptions)
13
* This is what users provide in jest.config.js or package.json
14
*/
15
interface Config {
16
// Test discovery
17
testMatch?: Array<string>;
18
testRegex?: string | Array<string>;
19
testPathIgnorePatterns?: Array<string>;
20
21
// Test environment
22
testEnvironment?: string;
23
testEnvironmentOptions?: Record<string, any>;
24
25
// Module resolution
26
moduleDirectories?: Array<string>;
27
moduleFileExtensions?: Array<string>;
28
moduleNameMapper?: Record<string, string>;
29
modulePaths?: Array<string>;
30
31
// Transforms
32
transform?: Record<string, string>;
33
transformIgnorePatterns?: Array<string>;
34
35
// Setup
36
setupFiles?: Array<string>;
37
setupFilesAfterEnv?: Array<string>;
38
39
// Coverage
40
collectCoverage?: boolean;
41
collectCoverageFrom?: Array<string>;
42
coverageDirectory?: string;
43
coveragePathIgnorePatterns?: Array<string>;
44
coverageProvider?: "babel" | "v8";
45
coverageReporters?: Array<string>;
46
coverageThreshold?: Record<string, Record<string, number>>;
47
48
// Execution
49
maxWorkers?: number | string;
50
testTimeout?: number;
51
52
// Output
53
verbose?: boolean;
54
silent?: boolean;
55
56
// Project structure
57
rootDir?: string;
58
roots?: Array<string>;
59
projects?: Array<string | Config>;
60
}
61
62
/**
63
* Global configuration that applies to the entire Jest run
64
*/
65
interface Config.GlobalConfig {
66
bail: number;
67
changedFilesWithAncestor: boolean;
68
changedSince?: string;
69
ci: boolean;
70
collectCoverage: boolean;
71
collectCoverageFrom: Array<string>;
72
collectCoverageOnlyFrom?: Record<string, boolean>;
73
coverageDirectory: string;
74
coveragePathIgnorePatterns?: Array<string>;
75
coverageProvider: "babel" | "v8";
76
coverageReporters: Array<string>;
77
coverageThreshold?: Record<string, Record<string, number>>;
78
detectLeaks: boolean;
79
detectOpenHandles: boolean;
80
errorOnDeprecated: boolean;
81
expand: boolean;
82
filter?: string;
83
findRelatedTests: boolean;
84
forceExit: boolean;
85
json: boolean;
86
globalSetup?: string;
87
globalTeardown?: string;
88
lastCommit: boolean;
89
listTests: boolean;
90
logHeapUsage: boolean;
91
maxConcurrency: number;
92
maxWorkers: number;
93
noSCM?: boolean;
94
noStackTrace: boolean;
95
notify: boolean;
96
notifyMode: string;
97
onlyChanged: boolean;
98
onlyFailures: boolean;
99
outputFile?: string;
100
passWithNoTests: boolean;
101
projects: Array<string>;
102
randomize?: boolean;
103
rootDir: string;
104
runTestsByPath: boolean;
105
seed?: number;
106
silent: boolean;
107
skipFilter: boolean;
108
testFailureExitCode: number;
109
testNamePattern?: string;
110
testPathPattern: string;
111
testPathPatterns: Array<string>;
112
testResultsProcessor?: string;
113
testSequencer: string;
114
testTimeout?: number;
115
updateSnapshot: SnapshotUpdateState;
116
useStderr: boolean;
117
verbose?: boolean;
118
watch: boolean;
119
watchAll: boolean;
120
watchPathIgnorePatterns: Array<string>;
121
watchman: boolean;
122
}
123
124
/**
125
* Per-project configuration
126
*/
127
interface Config.ProjectConfig {
128
automock: boolean;
129
cache: boolean;
130
cacheDirectory: string;
131
clearMocks: boolean;
132
collectCoverageFrom: Array<string>;
133
coveragePathIgnorePatterns: Array<string>;
134
cwd: string;
135
dependencyExtractor?: string;
136
detectLeaks: boolean;
137
displayName?: string;
138
errorOnDeprecated: boolean;
139
extensionsToTreatAsEsm: Array<string>;
140
extraGlobals: Array<string>;
141
forceCoverageMatch: Array<string>;
142
globalSetup?: string;
143
globalTeardown?: string;
144
globals: Record<string, unknown>;
145
haste: HasteConfig;
146
injectGlobals: boolean;
147
moduleDirectories: Array<string>;
148
moduleFileExtensions: Array<string>;
149
moduleNameMapper: Array<[string, string]>;
150
modulePaths?: Array<string>;
151
modulePathIgnorePatterns: Array<string>;
152
preset?: string;
153
prettierPath: string;
154
resetMocks: boolean;
155
resetModules: boolean;
156
resolver?: string;
157
restoreMocks: boolean;
158
rootDir: string;
159
roots: Array<string>;
160
runner: string;
161
setupFiles: Array<string>;
162
setupFilesAfterEnv: Array<string>;
163
skipFilter: boolean;
164
skipNodeResolution?: boolean;
165
slowTestThreshold: number;
166
snapshotResolver?: string;
167
snapshotSerializers: Array<string>;
168
testEnvironment: string;
169
testEnvironmentOptions: Record<string, unknown>;
170
testLocationInResults: boolean;
171
testMatch: Array<string>;
172
testPathIgnorePatterns: Array<string>;
173
testRegex: Array<string | RegExp>;
174
testRunner: string;
175
testURL?: string;
176
timers: "real" | "fake";
177
transform: Array<[string, string, Record<string, unknown>]>;
178
transformIgnorePatterns: Array<string>;
179
unmockedModulePathPatterns?: Array<string>;
180
watchPathIgnorePatterns: Array<string>;
181
}
182
183
/**
184
* Command line arguments interface
185
*/
186
interface Config.Argv {
187
// Test execution
188
all?: boolean;
189
bail?: boolean | number;
190
ci?: boolean;
191
findRelatedTests?: boolean;
192
listTests?: boolean;
193
onlyChanged?: boolean;
194
onlyFailures?: boolean;
195
passWithNoTests?: boolean;
196
runInBand?: boolean;
197
runTestsByPath?: boolean;
198
testNamePattern?: string;
199
testPathPatterns?: Array<string>;
200
testTimeout?: number;
201
202
// Watch mode
203
watch?: boolean;
204
watchAll?: boolean;
205
watchPathIgnorePatterns?: Array<string>;
206
207
// Coverage
208
collectCoverage?: boolean;
209
coverage?: boolean;
210
collectCoverageFrom?: Array<string>;
211
coverageDirectory?: string;
212
coveragePathIgnorePatterns?: Array<string>;
213
coverageProvider?: "babel" | "v8";
214
coverageReporters?: Array<string>;
215
coverageThreshold?: Record<string, number>;
216
217
// Output
218
json?: boolean;
219
outputFile?: string;
220
verbose?: boolean;
221
silent?: boolean;
222
noStackTrace?: boolean;
223
color?: boolean;
224
colors?: boolean;
225
226
// Configuration
227
config?: string;
228
rootDir?: string;
229
roots?: Array<string>;
230
projects?: Array<string>;
231
maxWorkers?: number | string;
232
cache?: boolean;
233
clearCache?: boolean;
234
debug?: boolean;
235
updateSnapshot?: boolean;
236
}
237
```
238
239
### Configuration File Examples
240
241
**Basic Configuration (jest.config.js):**
242
243
```javascript
244
module.exports = {
245
// Test discovery
246
testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
247
testPathIgnorePatterns: ["/node_modules/", "/build/"],
248
249
// Test environment
250
testEnvironment: "jsdom",
251
252
// Module resolution
253
moduleDirectories: ["node_modules", "src"],
254
moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx"],
255
moduleNameMapper: {
256
"^@/(.*)$": "<rootDir>/src/$1",
257
"\\.(css|less|scss)$": "identity-obj-proxy"
258
},
259
260
// Transforms
261
transform: {
262
"^.+\\.jsx?$": "babel-jest",
263
"^.+\\.tsx?$": "ts-jest"
264
},
265
266
// Setup
267
setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],
268
269
// Coverage
270
collectCoverage: true,
271
collectCoverageFrom: [
272
"src/**/*.{js,jsx,ts,tsx}",
273
"!src/**/*.d.ts",
274
"!src/index.js"
275
],
276
coverageDirectory: "coverage",
277
coverageReporters: ["text", "lcov", "html"],
278
coverageThreshold: {
279
global: {
280
branches: 80,
281
functions: 80,
282
lines: 80,
283
statements: 80
284
}
285
}
286
};
287
```
288
289
**TypeScript Configuration:**
290
291
```javascript
292
module.exports = {
293
preset: "ts-jest",
294
testEnvironment: "node",
295
296
// TypeScript specific
297
globals: {
298
"ts-jest": {
299
tsconfig: "tsconfig.test.json"
300
}
301
},
302
303
// Module resolution for TypeScript
304
moduleNameMapper: {
305
"^@/(.*)$": "<rootDir>/src/$1"
306
},
307
308
// File extensions
309
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json"],
310
311
// Transform configuration
312
transform: {
313
"^.+\\.tsx?$": "ts-jest"
314
},
315
316
// Test files
317
testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"]
318
};
319
```
320
321
**Multi-Project Configuration:**
322
323
```javascript
324
module.exports = {
325
projects: [
326
{
327
displayName: "client",
328
testMatch: ["<rootDir>/packages/client/**/*.test.js"],
329
testEnvironment: "jsdom",
330
setupFilesAfterEnv: ["<rootDir>/packages/client/src/setupTests.js"]
331
},
332
{
333
displayName: "server",
334
testMatch: ["<rootDir>/packages/server/**/*.test.js"],
335
testEnvironment: "node",
336
setupFilesAfterEnv: ["<rootDir>/packages/server/src/setupTests.js"]
337
},
338
{
339
displayName: "shared",
340
testMatch: ["<rootDir>/packages/shared/**/*.test.js"],
341
testEnvironment: "node"
342
}
343
],
344
345
// Global coverage settings
346
collectCoverage: true,
347
coverageDirectory: "coverage",
348
coverageReporters: ["text-summary", "html"]
349
};
350
```
351
352
### Configuration Loading and Resolution
353
354
Jest resolves configuration in the following order:
355
356
1. `--config` CLI argument
357
2. `jest.config.js` file
358
3. `jest.config.ts` file
359
4. `jest` field in `package.json`
360
5. Default configuration
361
362
**Programmatic Configuration:**
363
364
```typescript
365
import { runCLI, buildArgv } from "jest";
366
367
// Override configuration programmatically
368
async function runWithCustomConfig() {
369
const customConfig = {
370
testMatch: ["**/*.custom.test.js"],
371
testEnvironment: "node",
372
collectCoverage: true
373
};
374
375
const argv = await buildArgv([
376
`--config=${JSON.stringify(customConfig)}`
377
]);
378
379
return runCLI(argv, [process.cwd()]);
380
}
381
382
// Merge with existing configuration
383
async function extendConfiguration(baseConfigPath: string) {
384
const baseConfig = require(baseConfigPath);
385
386
const extendedConfig = {
387
...baseConfig,
388
collectCoverage: true,
389
coverageThreshold: {
390
global: {
391
branches: 90,
392
functions: 90,
393
lines: 90,
394
statements: 90
395
}
396
}
397
};
398
399
const argv = await buildArgv([
400
`--config=${JSON.stringify(extendedConfig)}`
401
]);
402
403
return runCLI(argv, [process.cwd()]);
404
}
405
```
406
407
### Environment-Specific Configuration
408
409
**Development Configuration:**
410
411
```javascript
412
// jest.dev.config.js
413
module.exports = {
414
...require('./jest.config.js'),
415
416
// Development specific settings
417
verbose: true,
418
collectCoverage: false,
419
watchAll: true,
420
421
// Faster transforms for development
422
transform: {
423
"^.+\\.jsx?$": "babel-jest"
424
}
425
};
426
```
427
428
**CI Configuration:**
429
430
```javascript
431
// jest.ci.config.js
432
module.exports = {
433
...require('./jest.config.js'),
434
435
// CI specific settings
436
ci: true,
437
collectCoverage: true,
438
coverageReporters: ["text", "lcov"],
439
maxWorkers: "50%",
440
cache: false,
441
442
// Strict coverage requirements
443
coverageThreshold: {
444
global: {
445
branches: 90,
446
functions: 90,
447
lines: 90,
448
statements: 90
449
}
450
}
451
};
452
```
453
454
### Advanced Configuration Patterns
455
456
**Dynamic Configuration:**
457
458
```javascript
459
// jest.config.js
460
const isCI = process.env.CI === "true";
461
const isDevelopment = process.env.NODE_ENV === "development";
462
463
module.exports = {
464
testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
465
466
// Dynamic coverage settings
467
collectCoverage: isCI,
468
coverageReporters: isCI
469
? ["text", "lcov"]
470
: ["text-summary"],
471
472
// Dynamic worker settings
473
maxWorkers: isCI ? "50%" : 1,
474
475
// Development specific settings
476
verbose: isDevelopment,
477
silent: isCI,
478
479
// Environment specific transforms
480
transform: isDevelopment
481
? { "^.+\\.jsx?$": "babel-jest" }
482
: { "^.+\\.jsx?$": ["babel-jest", { cacheDirectory: false }] }
483
};
484
```
485
486
**Conditional Test Patterns:**
487
488
```javascript
489
module.exports = {
490
// Base test patterns
491
testMatch: ["**/__tests__/**/*.js"],
492
493
// Add integration tests in CI
494
...(process.env.CI && {
495
testMatch: [
496
"**/__tests__/**/*.js",
497
"**/integration/**/*.test.js"
498
]
499
}),
500
501
// Add e2e tests for full test runs
502
...(process.env.FULL_TEST_SUITE && {
503
testMatch: [
504
"**/__tests__/**/*.js",
505
"**/integration/**/*.test.js",
506
"**/e2e/**/*.test.js"
507
]
508
})
509
};
510
```
511
512
Jest's configuration system provides complete control over test execution behavior, enabling optimization for different environments and use cases while maintaining consistency across development workflows.