0
# Command Line Interface
1
2
Complete command-line tools for instrumenting code, running tests with coverage, and generating reports. The Istanbul CLI provides a comprehensive set of commands for all coverage workflow needs.
3
4
## Capabilities
5
6
### CLI Entry Point
7
8
The main CLI interface processes commands and options.
9
10
```javascript { .api }
11
/**
12
* CLI runner that processes command line arguments
13
* @param {string[]} args - Command line arguments (process.argv.slice(2))
14
*/
15
function runToCompletion(args: string[]): void;
16
```
17
18
### Available Commands
19
20
Istanbul provides several commands accessible via the `istanbul` binary:
21
22
#### cover Command
23
24
Transparently adds coverage to Node.js command execution.
25
26
```bash
27
istanbul cover [options] <node-command> [-- <node-command-options>]
28
```
29
30
**Purpose:** Runs a Node.js command with coverage tracking enabled, automatically instrumenting required modules and generating reports.
31
32
**Options:**
33
- `--config <file>` - Configuration file path (defaults to .istanbul.yml)
34
- `--root <path>` - Root path to look for files to instrument (defaults to .)
35
- `-x <exclude-pattern>` - One or more glob patterns to exclude (e.g. "**/vendor/**")
36
- `-i <include-pattern>` - One or more glob patterns to include (e.g. "**/*.js")
37
- `--[no-]default-excludes` - Apply default excludes [**/node_modules/**, **/test/**, **/tests/**] (defaults to true)
38
- `--hook-run-in-context` - Hook vm.runInThisContext in addition to require (supports RequireJS, defaults to false)
39
- `--post-require-hook <file|module>` - JS module that exports a function for post-require processing
40
- `--report <format>` - Report format, can specify multiple times (defaults to lcov)
41
- `--dir <report-dir>` - Report directory (defaults to ./coverage)
42
- `--print <type>` - Type of report to print to console: summary (default), detail, both, or none
43
- `--verbose, -v` - Verbose mode
44
- `--[no-]preserve-comments` - Remove/preserve comments in output (defaults to false)
45
- `--include-all-sources` - Instrument all unused sources after running tests (defaults to false)
46
- `--[no-]include-pid` - Include PID in output coverage filename
47
48
**Examples:**
49
50
```bash
51
# Run tests with coverage
52
istanbul cover node_modules/.bin/mocha
53
54
# Run with custom options
55
istanbul cover --dir ./coverage --report html --report lcov node_modules/.bin/mocha
56
57
# Run Node.js script with coverage
58
istanbul cover -- node app.js --port 3000
59
60
# Include all source files
61
istanbul cover --include-all-sources node_modules/.bin/mocha
62
```
63
64
#### instrument Command
65
66
Instruments JavaScript files for coverage tracking.
67
68
```bash
69
istanbul instrument [options] <input-directory-or-file> [<output-directory>]
70
```
71
72
**Purpose:** Pre-instruments JavaScript files by transforming them to add coverage tracking code.
73
74
**Options:**
75
- `--config <path-to-config>` - Configuration file to use (defaults to .istanbul.yml)
76
- `--output <file-or-dir>` - Output file or directory (required when input is a directory, defaults to stdout for files)
77
- `-x <exclude-pattern>` - One or more glob patterns to exclude (e.g. "**/vendor/**")
78
- `--variable <global-coverage-variable-name>` - Change global coverage variable name from default `__coverage__`
79
- `--embed-source` - Embed source code into the coverage object (defaults to false)
80
- `--[no-]compact` - Produce [non]compact output (defaults to compact)
81
- `--[no-]preserve-comments` - Remove/preserve comments in output (defaults to false)
82
- `--[no-]complete-copy` - Also copy non-javascript files to output directory as is (defaults to false)
83
- `--save-baseline` - Produce a baseline coverage.json file out of all files instrumented
84
- `--baseline-file <file>` - Filename of baseline file (defaults to coverage/coverage-baseline.json)
85
- `--es-modules` - Source code uses ES import/export module syntax
86
- `--[no-]auto-wrap` - Whether to wrap code in anonymous function (defaults to true)
87
88
**Examples:**
89
90
```bash
91
# Instrument directory
92
istanbul instrument src/ instrumented/
93
94
# Instrument single file
95
istanbul instrument app.js --output instrumented/
96
97
# Instrument with options
98
istanbul instrument --embed-source --preserve-comments src/ build/
99
100
# Copy all files, not just JS
101
istanbul instrument --complete-copy src/ dist/
102
```
103
104
#### report Command
105
106
Generates reports from coverage JSON files.
107
108
```bash
109
istanbul report [options] [<report-format>...]
110
```
111
112
**Purpose:** Generates coverage reports in various formats from existing coverage data files.
113
114
**Options:**
115
- `--config <file>` - Configuration file path
116
- `--dir <directory>` - Output directory for reports
117
- `--root <directory>` - Root directory for resolving file paths
118
- `--include <pattern>` - Include file patterns
119
- `--exclude <pattern>` - Exclude file patterns
120
121
**Available Formats:**
122
- `text` - Text-based console output
123
- `text-summary` - Summary text output
124
- `html` - Interactive HTML report
125
- `lcov` - LCOV format (HTML + tracefile)
126
- `lcovonly` - LCOV tracefile only
127
- `json` - Raw JSON coverage data
128
- `json-summary` - JSON summary metrics
129
- `clover` - Clover XML format
130
- `cobertura` - Cobertura XML format
131
- `teamcity` - TeamCity service messages
132
133
**Examples:**
134
135
```bash
136
# Generate HTML report
137
istanbul report html
138
139
# Generate multiple formats
140
istanbul report html lcov json-summary
141
142
# Generate with custom directory
143
istanbul report --dir ./reports html
144
145
# Generate from specific coverage files
146
istanbul report --dir ./reports text < coverage/coverage.json
147
```
148
149
#### check-coverage Command
150
151
Validates coverage against configured thresholds.
152
153
```bash
154
istanbul check-coverage [options]
155
```
156
157
**Purpose:** Checks coverage percentages against minimum thresholds and exits with error if thresholds are not met.
158
159
**Options:**
160
- `--config <file>` - Configuration file path
161
- `--statements <percentage>` - Statement coverage threshold
162
- `--branches <percentage>` - Branch coverage threshold
163
- `--functions <percentage>` - Function coverage threshold
164
- `--lines <percentage>` - Line coverage threshold
165
- `--include <pattern>` - Include file patterns
166
- `--exclude <pattern>` - Exclude file patterns
167
168
**Examples:**
169
170
```bash
171
# Check with default thresholds from config
172
istanbul check-coverage
173
174
# Set custom thresholds
175
istanbul check-coverage --statements 90 --branches 80 --functions 95 --lines 85
176
177
# Check specific files only
178
istanbul check-coverage --statements 80 --include "src/**/*.js"
179
180
# Use in CI/CD pipeline
181
istanbul check-coverage --statements 85 --branches 75 || exit 1
182
```
183
184
#### help Command
185
186
Shows help information for commands.
187
188
```bash
189
istanbul help [command]
190
```
191
192
**Examples:**
193
194
```bash
195
# General help
196
istanbul help
197
198
# Command-specific help
199
istanbul help cover
200
istanbul help instrument
201
istanbul help report
202
```
203
204
#### test Command
205
206
Runs tests with coverage using specific test frameworks.
207
208
```bash
209
istanbul test [options] <test-framework> [-- <test-options>]
210
```
211
212
**Purpose:** Runs tests using specified test framework with coverage enabled.
213
214
**Supported Frameworks:**
215
- `mocha`
216
- `nodeunit`
217
- `jasmine-node`
218
- Custom test commands
219
220
**Examples:**
221
222
```bash
223
# Run Mocha tests with coverage
224
istanbul test mocha
225
226
# Run with test options
227
istanbul test mocha -- --recursive test/
228
229
# Run custom test command
230
istanbul test -- node custom-test-runner.js
231
```
232
233
### Configuration Files
234
235
Istanbul commands can use configuration files in YAML or JSON format:
236
237
**`.istanbul.yml` Example:**
238
239
```yaml
240
instrumentation:
241
default-excludes: true
242
excludes: ['**/test/**', '**/*.test.js']
243
embed-source: false
244
variable: '__coverage__'
245
compact: true
246
preserve-comments: false
247
complete-copy: false
248
save-baseline: false
249
include-all-sources: false
250
include-pid: false
251
252
reporting:
253
print: summary
254
reports: ['text-summary', 'html', 'lcov']
255
dir: ./coverage
256
watermarks:
257
statements: [50, 80]
258
branches: [50, 80]
259
functions: [50, 80]
260
lines: [50, 80]
261
262
hooks:
263
hook-run-in-context: false
264
post-require-hook: null
265
handle-sigint: true
266
267
check:
268
global:
269
statements: 80
270
branches: 75
271
functions: 85
272
lines: 80
273
```
274
275
### Workflow Examples
276
277
#### Basic Test Coverage Workflow
278
279
```bash
280
# 1. Run tests with coverage
281
istanbul cover node_modules/.bin/mocha
282
283
# 2. Check coverage thresholds
284
istanbul check-coverage --statements 80 --branches 70
285
286
# 3. Generate additional report formats
287
istanbul report html lcov
288
```
289
290
#### Pre-instrumentation Workflow
291
292
```bash
293
# 1. Instrument source code
294
istanbul instrument src/ instrumented/
295
296
# 2. Run tests against instrumented code
297
NODE_PATH=instrumented npm test
298
299
# 3. Generate reports from coverage data
300
istanbul report html text-summary
301
302
# 4. Check thresholds
303
istanbul check-coverage
304
```
305
306
#### CI/CD Integration
307
308
```bash
309
#!/bin/bash
310
# coverage.sh - CI/CD coverage script
311
312
set -e
313
314
echo "Running tests with coverage..."
315
istanbul cover --include-all-sources node_modules/.bin/mocha
316
317
echo "Checking coverage thresholds..."
318
istanbul check-coverage \
319
--statements 85 \
320
--branches 75 \
321
--functions 90 \
322
--lines 85
323
324
echo "Generating reports..."
325
istanbul report html lcov json-summary
326
327
echo "Coverage analysis complete!"
328
```
329
330
### Advanced Usage
331
332
#### Custom Configuration per Environment
333
334
```bash
335
# Development - detailed reporting
336
istanbul cover --config .istanbul.dev.yml node_modules/.bin/mocha
337
338
# CI - minimal reporting, strict thresholds
339
istanbul cover --config .istanbul.ci.yml node_modules/.bin/mocha
340
istanbul check-coverage --config .istanbul.ci.yml
341
```
342
343
#### Programmatic CLI Usage
344
345
```javascript
346
const { runToCompletion } = require('istanbul/lib/cli');
347
348
// Run CLI programmatically
349
try {
350
runToCompletion(['cover', 'node_modules/.bin/mocha']);
351
console.log('Coverage run completed successfully');
352
} catch (error) {
353
console.error('Coverage run failed:', error.message);
354
process.exit(1);
355
}
356
```
357
358
### Integration with Build Tools
359
360
#### NPM Scripts
361
362
```json
363
{
364
"scripts": {
365
"test": "mocha",
366
"test:coverage": "istanbul cover node_modules/.bin/mocha",
367
"coverage:check": "istanbul check-coverage --statements 80 --branches 70",
368
"coverage:report": "istanbul report html",
369
"coverage:all": "npm run test:coverage && npm run coverage:check && npm run coverage:report"
370
}
371
}
372
```
373
374
#### Grunt Integration
375
376
```javascript
377
// Gruntfile.js
378
module.exports = function(grunt) {
379
grunt.loadNpmTasks('grunt-exec');
380
381
grunt.initConfig({
382
exec: {
383
coverage: {
384
cmd: 'istanbul cover node_modules/.bin/mocha'
385
},
386
coverage_check: {
387
cmd: 'istanbul check-coverage --statements 80'
388
}
389
}
390
});
391
392
grunt.registerTask('test:coverage', ['exec:coverage', 'exec:coverage_check']);
393
};
394
```
395
396
#### Gulp Integration
397
398
```javascript
399
// gulpfile.js
400
const gulp = require('gulp');
401
const { spawn } = require('child_process');
402
403
gulp.task('coverage', (done) => {
404
const istanbul = spawn('istanbul', ['cover', 'node_modules/.bin/mocha'], {
405
stdio: 'inherit'
406
});
407
408
istanbul.on('close', (code) => {
409
if (code === 0) {
410
done();
411
} else {
412
done(new Error(`Istanbul exited with code ${code}`));
413
}
414
});
415
});
416
417
gulp.task('coverage:check', (done) => {
418
const check = spawn('istanbul', ['check-coverage', '--statements', '80'], {
419
stdio: 'inherit'
420
});
421
422
check.on('close', (code) => {
423
done(code === 0 ? null : new Error('Coverage thresholds not met'));
424
});
425
});
426
```
427
428
### Troubleshooting
429
430
#### Common Issues and Solutions
431
432
```bash
433
# Issue: Module not found errors
434
# Solution: Use correct paths and NODE_PATH
435
NODE_PATH=./instrumented istanbul cover node_modules/.bin/mocha
436
437
# Issue: ES6 modules not supported
438
# Solution: Enable ES modules flag
439
istanbul cover --es-modules node_modules/.bin/mocha
440
441
# Issue: Coverage data not found
442
# Solution: Ensure coverage variable is accessible
443
istanbul cover --variable __coverage__ node_modules/.bin/mocha
444
445
# Issue: Permission errors on output directory
446
# Solution: Create directory or fix permissions
447
mkdir -p coverage
448
chmod 755 coverage
449
istanbul cover --dir ./coverage node_modules/.bin/mocha
450
```
451
452
#### Debug Mode
453
454
```bash
455
# Enable debug output
456
DEBUG=istanbul:* istanbul cover node_modules/.bin/mocha
457
458
# Verbose configuration output
459
istanbul cover --verbose node_modules/.bin/mocha
460
```
461
462
### Exit Codes
463
464
Istanbul CLI commands use standard exit codes:
465
466
- `0` - Success
467
- `1` - General error (missing files, invalid options, etc.)
468
- `2` - Coverage thresholds not met (check-coverage command)
469
- `3` - Configuration error
470
- `4` - Instrumentation error
471
472
**Example Exit Code Handling:**
473
474
```bash
475
#!/bin/bash
476
istanbul check-coverage --statements 80 --branches 70
477
EXIT_CODE=$?
478
479
case $EXIT_CODE in
480
0)
481
echo "Coverage thresholds met"
482
;;
483
2)
484
echo "Coverage thresholds not met"
485
exit 1
486
;;
487
*)
488
echo "Coverage check failed with code $EXIT_CODE"
489
exit $EXIT_CODE
490
;;
491
esac
492
```