0
# CLI Usage
1
2
Jest provides a comprehensive command-line interface with over 70 options for controlling test execution, coverage collection, watch mode, output formatting, and project configuration.
3
4
## Basic CLI Usage
5
6
Jest can be run from the command line with various options:
7
8
```bash
9
# Run all tests
10
jest
11
12
# Run tests matching a pattern
13
jest MyComponent
14
15
# Run tests in a specific directory
16
jest src/components
17
18
# Run tests with coverage
19
jest --coverage
20
21
# Run tests in watch mode
22
jest --watch
23
```
24
25
## CLI Options Reference
26
27
### Test Execution Options
28
29
Control how tests are discovered, executed, and filtered.
30
31
```bash
32
# Stop after N test failures
33
jest --bail
34
jest --bail=3
35
36
# Find tests related to specified files
37
jest --findRelatedTests src/utils.js src/components/Button.js
38
39
# List all tests Jest will run without executing them
40
jest --listTests
41
42
# Only run tests related to changed files (requires git)
43
jest --onlyChanged
44
jest -o
45
46
# Run only tests that failed in previous execution
47
jest --onlyFailures
48
jest -f
49
50
# Don't fail when no tests are found
51
jest --passWithNoTests
52
53
# Run tests serially in current process instead of parallel workers
54
jest --runInBand
55
jest -i
56
57
# Use exact file paths instead of patterns
58
jest --runTestsByPath path/to/test1.js path/to/test2.js
59
60
# Run tests matching name pattern (regex)
61
jest --testNamePattern="should add"
62
jest -t "user login"
63
64
# Regexp patterns for test file paths
65
jest --testPathPatterns="__tests__.*\.js$"
66
67
# Override testRegex configuration
68
jest --testRegex=".*\.(test|spec)\.(js|ts)$"
69
70
# Set default test timeout in milliseconds
71
jest --testTimeout=10000
72
```
73
74
### Watch Mode Options
75
76
Configure file watching and automatic test re-execution.
77
78
```bash
79
# Watch files and rerun related tests on changes
80
jest --watch
81
82
# Watch files and rerun all tests on changes
83
jest --watchAll
84
85
# Ignore patterns for watch mode
86
jest --watchPathIgnorePatterns="node_modules" --watchPathIgnorePatterns="build"
87
```
88
89
## Testing Options
90
91
### Test Selection and Filtering
92
93
```bash
94
# Run only tests that failed in the previous run
95
jest --onlyFailures
96
97
# Run only tests related to changed files (requires git)
98
jest --onlyChanged
99
100
# Run tests related to specific files
101
jest --findRelatedTests src/utils.js src/components/Button.js
102
103
# Run tests matching a name pattern
104
jest --testNamePattern="should render correctly"
105
106
# List all tests Jest would run without executing them
107
jest --listTests
108
109
# Run tests by exact file paths instead of patterns
110
jest --runTestsByPath
111
```
112
113
### Test Execution Control
114
115
```bash
116
# Stop after N test failures
117
jest --bail
118
jest --bail=3
119
120
# Run tests serially in the current process
121
jest --runInBand
122
123
# Set maximum number of worker processes
124
jest --maxWorkers=4
125
jest --maxWorkers=50%
126
127
# Set default timeout for tests
128
jest --testTimeout=10000
129
130
# Don't fail when no tests are found
131
jest --passWithNoTests
132
```
133
134
## Coverage Options
135
136
### Basic Coverage
137
138
```bash
139
# Collect and report test coverage
140
jest --coverage
141
jest --collectCoverage # equivalent
142
143
# Specify coverage output directory
144
jest --coverageDirectory=coverage-report
145
146
# Choose coverage provider
147
jest --coverageProvider=babel
148
jest --coverageProvider=v8
149
```
150
151
### Coverage Configuration
152
153
```bash
154
# Collect coverage from specific files
155
jest --collectCoverageFrom="src/**/*.js" --collectCoverageFrom="!src/**/*.test.js"
156
157
# Ignore patterns for coverage
158
jest --coveragePathIgnorePatterns=node_modules --coveragePathIgnorePatterns=build
159
160
# Specify coverage reporters
161
jest --coverageReporters=text --coverageReporters=html --coverageReporters=lcov
162
163
# Set coverage thresholds (will fail if not met)
164
jest --coverageThreshold='{"global":{"branches":80,"functions":80,"lines":80,"statements":80}}'
165
```
166
167
## Output and Reporting
168
169
### Output Formats
170
171
```bash
172
# Output results in JSON format
173
jest --json
174
175
# Write JSON output to a file
176
jest --json --outputFile=test-results.json
177
178
# Verbose output showing individual test results
179
jest --verbose
180
181
# Silent mode - prevent tests from printing to console
182
jest --silent
183
184
# Disable stack traces in test output
185
jest --noStackTrace
186
187
# Force colored output
188
jest --colors
189
```
190
191
### Advanced Output Control
192
193
```bash
194
# Log heap usage after each test
195
jest --logHeapUsage
196
197
# Detect and report memory leaks (experimental)
198
jest --detectLeaks
199
200
# Detect handles that prevent Jest from exiting
201
jest --detectOpenHandles
202
203
# Force Jest to exit after tests complete
204
jest --forceExit
205
```
206
207
## Configuration Options
208
209
### Configuration Sources
210
211
```bash
212
# Use specific config file
213
jest --config=jest.config.js
214
jest --config=package.json
215
216
# Provide configuration as JSON string
217
jest --config='{"testEnvironment":"node"}'
218
219
# Set root directory
220
jest --rootDir=/path/to/project
221
222
# Specify multiple root directories
223
jest --roots=src --roots=lib
224
225
# Run tests for multiple projects
226
jest --projects=project1 --projects=project2
227
```
228
229
### Environment and Setup
230
231
```bash
232
# Specify test environment
233
jest --testEnvironment=node
234
jest --testEnvironment=jsdom
235
236
# Clear all mocks before each test
237
jest --clearMocks
238
239
# Reset module registry before each test
240
jest --resetModules
241
242
# Restore mocks after each test
243
jest --restoreMocks
244
```
245
246
## Cache Management
247
248
```bash
249
# Use the transform cache (default: true)
250
jest --cache
251
252
# Disable the transform cache
253
jest --no-cache
254
255
# Specify cache directory
256
jest --cacheDirectory=/tmp/jest-cache
257
258
# Clear cache and exit (useful for CI)
259
jest --clearCache
260
```
261
262
## Advanced Options
263
264
### Development and Debugging
265
266
```bash
267
# Enable debug mode
268
jest --debug
269
270
# Throw error on deprecated API usage
271
jest --errorOnDeprecated
272
273
# Update snapshots
274
jest --updateSnapshot
275
276
# Randomize test order within files
277
jest --randomize
278
279
# Set seed for test randomization
280
jest --seed=12345
281
```
282
283
### Performance and Concurrency
284
285
```bash
286
# Set maximum concurrent tests when using test.concurrent
287
jest --maxConcurrency=5
288
289
# Use specific number of workers
290
jest --maxWorkers=2
291
292
# Run tests in band (single process) for debugging
293
jest -i # short for --runInBand
294
```
295
296
## Watch Mode Patterns
297
298
When running in watch mode (`--watch` or `--watchAll`), Jest provides an interactive interface:
299
300
```bash
301
# Watch mode commands (available during watch mode):
302
# Press 'a' to run all tests
303
# Press 'f' to run only failed tests
304
# Press 'o' to only run tests related to changed files
305
# Press 'p' to filter by a filename regex pattern
306
# Press 't' to filter by a test name regex pattern
307
# Press 'q' to quit watch mode
308
# Press 'Enter' to trigger a test run
309
```
310
311
### Watch Mode Configuration
312
313
```bash
314
# Ignore patterns in watch mode
315
jest --watch --watchPathIgnorePatterns=node_modules --watchPathIgnorePatterns=build
316
317
# Watch all files (not just tracked by git)
318
jest --watchAll
319
320
# Combine with other options
321
jest --watch --coverage --verbose
322
```
323
324
## CLI Argument Building Programmatically
325
326
```typescript { .api }
327
import { buildArgv } from 'jest';
328
329
function buildArgv(maybeArgv?: Array<string>): Promise<Config.Argv>
330
```
331
332
You can build CLI arguments programmatically using the `buildArgv` function:
333
334
```typescript
335
import { buildArgv, runCLI } from 'jest';
336
337
// Build arguments for CI environment
338
const ciArgv = await buildArgv([
339
'--ci',
340
'--coverage',
341
'--json',
342
'--runInBand',
343
'--passWithNoTests',
344
'--outputFile=test-results.json'
345
]);
346
347
// Build arguments for development
348
const devArgv = await buildArgv([
349
'--watch',
350
'--verbose',
351
'--testPathPatterns=src/'
352
]);
353
354
// Build arguments with coverage thresholds
355
const strictArgv = await buildArgv([
356
'--coverage',
357
'--coverageThreshold={"global":{"branches":90,"functions":90,"lines":90,"statements":90}}'
358
]);
359
```
360
361
## Common CLI Workflows
362
363
### Continuous Integration
364
365
```bash
366
# Typical CI command
367
jest --ci --coverage --json --runInBand --passWithNoTests --outputFile=results.json
368
369
# With coverage enforcement
370
jest --ci --coverage --coverageThreshold='{"global":{"branches":80,"functions":80,"lines":80,"statements":80}}'
371
```
372
373
### Development Workflow
374
375
```bash
376
# Start development with watch mode
377
jest --watch --verbose
378
379
# Run tests for specific feature
380
jest --watch --testPathPatterns=src/features/auth
381
382
# Debug failing tests
383
jest --runInBand --verbose --testNamePattern="failing test name"
384
```
385
386
### Pre-commit Checks
387
388
```bash
389
# Run only tests related to staged files
390
jest --onlyChanged --passWithNoTests
391
392
# Full validation with coverage
393
jest --coverage --bail=1
394
```
395
396
### Performance Analysis
397
398
```bash
399
# Analyze test performance
400
jest --verbose --logHeapUsage --detectLeaks
401
402
# Profile with single worker for consistency
403
jest --runInBand --logHeapUsage
404
```
405
406
The Jest CLI provides comprehensive control over test execution, making it suitable for development, continuous integration, and automated testing workflows.