0
# CLI and Configuration
1
2
Command-line interface and comprehensive configuration system for running tests from the command line with file watching, parallel execution, and extensive customization options.
3
4
## Capabilities
5
6
### Command Line Interface
7
8
Main CLI executable for running tests from the command line.
9
10
```bash { .api }
11
# Basic usage
12
mocha [options] [files]
13
14
# Common usage patterns
15
mocha # Run all tests in test/ directory
16
mocha test/**/*.spec.js # Run specific test files
17
mocha --grep "User" # Run tests matching pattern
18
mocha --reporter json # Use specific reporter
19
mocha --timeout 5000 # Set global timeout
20
mocha --watch # Watch files for changes
21
mocha --parallel # Run tests in parallel
22
```
23
24
### CLI Options
25
26
Comprehensive command-line options for test configuration.
27
28
```bash { .api }
29
# Test Selection and Filtering
30
--grep <pattern> # Filter tests by pattern (string or regex)
31
--fgrep <string> # Filter tests by fixed string
32
--invert # Invert grep pattern
33
--recursive # Look for tests in subdirectories
34
35
# Test Execution
36
--timeout <ms> # Set global timeout (default: 2000ms)
37
--slow <ms> # Set slow test threshold (default: 75ms)
38
--retries <count> # Set retry count for failed tests
39
--bail # Bail on first test failure
40
--parallel # Run tests in parallel
41
--jobs <count> # Number of parallel jobs (default: CPU count - 1)
42
43
# Interfaces and Reporters
44
--ui <name> # Set interface: bdd, tdd, qunit, exports
45
--reporter <name> # Set reporter (default: spec)
46
--reporter-option <key=value> # Pass options to reporter
47
48
# Test Behavior
49
--async-only # Force tests to be async
50
--allow-uncaught # Allow uncaught exceptions to propagate
51
--delay # Delay test execution until run() is called
52
--dry-run # Report tests without executing them
53
--exit # Force exit after tests complete
54
--forbid-only # Fail if .only tests are present
55
--forbid-pending # Fail if .skip tests are present
56
--full-trace # Display full stack traces
57
58
# Global Variables and Leaks
59
--check-leaks # Check for global variable leaks
60
--globals <names> # Specify global variables (comma-separated)
61
62
# Output and Formatting
63
--colors # Force color output
64
--no-colors # Disable color output
65
--diff # Show diff on test failure
66
--inline-diffs # Show inline diffs
67
--sort # Sort test files alphabetically
68
69
# File Operations
70
--watch # Watch files for changes and re-run tests
71
--watch-files <globs> # Specify files to watch (comma-separated)
72
--watch-ignore <globs> # Specify files to ignore when watching
73
--file <file> # Include file before other test files
74
--require <module> # Require module before running tests
75
--loader <loader> # Use custom loader for test files
76
77
# Configuration Files
78
--config <path> # Specify config file path
79
--package <path> # Specify package.json path
80
--opts <path> # Specify mocha.opts file (deprecated)
81
82
# Node.js Specific
83
--inspect # Enable Node.js inspector
84
--inspect-brk # Enable inspector and break before start
85
--node-option <option> # Pass option to Node.js
86
87
# Miscellaneous
88
--version # Show version
89
--help # Show help
90
--reporter-options <options> # (deprecated, use --reporter-option)
91
```
92
93
### Configuration Files
94
95
Mocha supports multiple configuration file formats.
96
97
```javascript { .api }
98
/**
99
* Configuration file formats and locations
100
*/
101
102
// .mocharc.json - JSON configuration
103
{
104
"ui": "bdd",
105
"reporter": "spec",
106
"timeout": 5000,
107
"slow": 100,
108
"recursive": true,
109
"require": ["test/setup.js"],
110
"grep": "User"
111
}
112
113
// .mocharc.yml - YAML configuration
114
ui: bdd
115
reporter: spec
116
timeout: 5000
117
slow: 100
118
recursive: true
119
require:
120
- test/setup.js
121
grep: User
122
123
// .mocharc.js - JavaScript configuration
124
module.exports = {
125
ui: 'bdd',
126
reporter: 'spec',
127
timeout: 5000,
128
slow: 100,
129
recursive: true,
130
require: ['test/setup.js'],
131
grep: 'User'
132
};
133
134
// package.json - mocha field
135
{
136
"mocha": {
137
"ui": "bdd",
138
"reporter": "spec",
139
"timeout": 5000,
140
"recursive": true
141
}
142
}
143
```
144
145
### Configuration Options Interface
146
147
Complete configuration options available programmatically and via config files.
148
149
```javascript { .api }
150
/**
151
* Complete Mocha configuration options
152
*/
153
interface MochaOptions {
154
// Test Selection
155
grep?: string | RegExp; // Filter tests by pattern
156
fgrep?: string; // Filter by fixed string
157
invert?: boolean; // Invert grep pattern
158
159
// Test Execution
160
timeout?: number; // Global timeout in ms
161
slow?: number; // Slow test threshold in ms
162
retries?: number; // Retry count for failed tests
163
bail?: boolean; // Bail on first failure
164
parallel?: boolean; // Enable parallel execution
165
jobs?: number; // Number of parallel jobs
166
167
// Interfaces and Reporting
168
ui?: string; // Test interface
169
reporter?: string | Function; // Reporter name or constructor
170
reporterOption?: object; // Reporter options
171
reporterOptions?: object; // Reporter options (legacy)
172
173
// Test Behavior
174
asyncOnly?: boolean; // Require async tests
175
allowUncaught?: boolean; // Allow uncaught exceptions
176
delay?: boolean; // Delay execution
177
dryRun?: boolean; // Don't execute tests
178
exit?: boolean; // Force exit after completion
179
forbidOnly?: boolean; // Forbid .only tests
180
forbidPending?: boolean; // Forbid .skip tests
181
fullTrace?: boolean; // Show full stack traces
182
183
// Global Variables
184
checkLeaks?: boolean; // Check for global leaks
185
globals?: string[]; // Global variables to ignore
186
187
// Output and Formatting
188
color?: boolean; // Enable colored output
189
colors?: boolean; // Alias for color
190
diff?: boolean; // Show diff on failure
191
inlineDiffs?: boolean; // Show inline diffs
192
sort?: boolean; // Sort test files
193
194
// File Operations
195
watch?: boolean; // Watch for file changes
196
watchFiles?: string[]; // Files to watch
197
watchIgnore?: string[]; // Files to ignore
198
file?: string[]; // Files to include first
199
require?: string[]; // Modules to require
200
loader?: string; // Custom loader
201
recursive?: boolean; // Search subdirectories
202
203
// Configuration
204
config?: string; // Config file path
205
package?: string; // package.json path
206
opts?: string; // mocha.opts file (deprecated)
207
208
// Root Hooks and Global Setup
209
rootHooks?: MochaRootHookObject; // Root hooks
210
globalSetup?: string | string[]; // Global setup functions
211
globalTeardown?: string | string[]; // Global teardown functions
212
enableGlobalSetup?: boolean; // Enable global setup
213
enableGlobalTeardown?: boolean; // Enable global teardown
214
215
// Advanced Options
216
isWorker?: boolean; // Running in worker process
217
serializer?: string; // Custom serializer for parallel mode
218
}
219
220
/**
221
* Root hooks object for global setup/teardown
222
*/
223
interface MochaRootHookObject {
224
beforeAll?: Function | Function[]; // Global before hooks
225
beforeEach?: Function | Function[]; // Global beforeEach hooks
226
afterAll?: Function | Function[]; // Global after hooks
227
afterEach?: Function | Function[]; // Global afterEach hooks
228
}
229
```
230
231
### File Watching
232
233
Automatic test re-execution when files change.
234
235
```bash { .api }
236
# Basic file watching
237
mocha --watch
238
239
# Watch specific files
240
mocha --watch --watch-files "src/**/*.js,test/**/*.js"
241
242
# Ignore files when watching
243
mocha --watch --watch-ignore "node_modules/**,dist/**"
244
245
# Watch with grep pattern
246
mocha --watch --grep "Unit"
247
```
248
249
```javascript { .api }
250
/**
251
* Programmatic file watching
252
*/
253
const mocha = new Mocha({
254
watch: true,
255
watchFiles: ['src/**/*.js', 'test/**/*.js'],
256
watchIgnore: ['node_modules/**', 'dist/**']
257
});
258
```
259
260
### Parallel Execution Configuration
261
262
Configure parallel test execution for improved performance.
263
264
```bash { .api }
265
# Enable parallel execution
266
mocha --parallel
267
268
# Set number of workers
269
mocha --parallel --jobs 4
270
271
# Parallel with other options
272
mocha --parallel --jobs 2 --timeout 10000 --reporter spec
273
```
274
275
```javascript { .api }
276
/**
277
* Parallel execution options
278
*/
279
interface ParallelOptions {
280
parallel: boolean; // Enable parallel execution
281
jobs?: number; // Number of worker processes
282
timeout?: number; // Worker timeout
283
workerTimeout?: number; // Worker-specific timeout
284
}
285
286
const mocha = new Mocha({
287
parallel: true,
288
jobs: 4,
289
timeout: 10000
290
});
291
```
292
293
### Module Loading and Requirements
294
295
Load modules and setup files before tests.
296
297
```bash { .api }
298
# Require modules before tests
299
mocha --require test/setup.js --require should
300
301
# Multiple requires
302
mocha --require babel-register --require test/helpers.js
303
304
# Include files before test files
305
mocha --file test/globals.js --file test/setup.js
306
```
307
308
```javascript { .api }
309
/**
310
* Module loading configuration
311
*/
312
interface ModuleLoadingOptions {
313
require?: string[]; // Modules to require before tests
314
file?: string[]; // Files to include before test files
315
loader?: string; // Custom loader for test files
316
}
317
318
// Example setup file (test/setup.js)
319
const chai = require('chai');
320
const sinon = require('sinon');
321
322
// Global setup
323
global.expect = chai.expect;
324
global.sinon = sinon;
325
326
// Configure chai
327
chai.config.includeStack = true;
328
chai.config.truncateThreshold = 0;
329
```
330
331
### Environment Variables
332
333
Environment variables that affect Mocha behavior.
334
335
```bash { .api }
336
# Common environment variables
337
MOCHA_COLORS=1 # Enable colors
338
MOCHA_GREP="pattern" # Set grep pattern
339
MOCHA_TIMEOUT=5000 # Set timeout
340
MOCHA_REPORTER=json # Set reporter
341
NODE_ENV=test # Set Node environment
342
DEBUG=mocha:* # Enable debug output
343
344
# Usage examples
345
MOCHA_TIMEOUT=10000 mocha test/
346
DEBUG=mocha:runner mocha --grep "slow tests"
347
```
348
349
### Configuration Precedence
350
351
Order of configuration precedence (highest to lowest):
352
353
```javascript { .api }
354
/**
355
* Configuration precedence order
356
* 1. Command line arguments (highest)
357
* 2. Environment variables
358
* 3. Configuration files (.mocharc.*)
359
* 4. package.json "mocha" field
360
* 5. Default values (lowest)
361
*/
362
363
// Example: timeout value resolution
364
// 1. --timeout 3000 (CLI)
365
// 2. MOCHA_TIMEOUT=4000 (env)
366
// 3. { "timeout": 5000 } (.mocharc.json)
367
// 4. { "mocha": { "timeout": 6000 } } (package.json)
368
// 5. 2000 (default)
369
// Result: 3000ms (CLI wins)
370
```
371
372
### Advanced CLI Usage
373
374
Complex CLI usage patterns and examples.
375
376
```bash { .api }
377
# Complex test execution
378
mocha test/unit/**/*.spec.js \
379
--require test/setup.js \
380
--require babel-register \
381
--grep "User" \
382
--reporter json \
383
--timeout 5000 \
384
--slow 100 \
385
--bail \
386
--check-leaks
387
388
# Parallel execution with custom options
389
mocha --parallel \
390
--jobs 4 \
391
--timeout 10000 \
392
--reporter spec \
393
--require test/setup.js \
394
"test/**/*.spec.js"
395
396
# Watch mode with filtering
397
mocha --watch \
398
--watch-files "src/**/*.js" \
399
--watch-ignore "dist/**" \
400
--grep "integration" \
401
--reporter min
402
403
# Browser test preparation
404
mocha --reporter json \
405
--timeout 30000 \
406
--slow 5000 \
407
test/browser/**/*.js > browser-test-results.json
408
409
# Debug mode with inspector
410
mocha --inspect-brk \
411
--timeout 0 \
412
--grep "specific test" \
413
test/debug.spec.js
414
```
415
416
### Legacy mocha.opts (Deprecated)
417
418
Legacy configuration file format (now deprecated in favor of .mocharc files).
419
420
```bash { .api }
421
# test/mocha.opts (deprecated)
422
--require test/setup.js
423
--require should
424
--reporter spec
425
--ui bdd
426
--timeout 5000
427
--colors
428
--recursive
429
test/**/*.spec.js
430
```
431
432
### Configuration Validation
433
434
Mocha validates configuration and provides helpful error messages.
435
436
```javascript { .api }
437
/**
438
* Configuration validation examples
439
*/
440
441
// Invalid reporter
442
mocha --reporter nonexistent
443
// Error: invalid reporter "nonexistent"
444
445
// Invalid timeout
446
mocha --timeout abc
447
// Error: timeout must be a number
448
449
// Conflicting options
450
mocha --forbid-only test/with-only.js
451
// Error: .only tests found but forbidden
452
453
// Invalid parallel configuration
454
mocha --parallel --bail
455
// Warning: --bail not supported in parallel mode
456
```