CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-istanbul

Comprehensive JavaScript code coverage tool that computes statement, line, function and branch coverage with module loader hooks for transparent instrumentation

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

cli.mddocs/

Command Line Interface

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.

Capabilities

CLI Entry Point

The main CLI interface processes commands and options.

/**
 * CLI runner that processes command line arguments
 * @param {string[]} args - Command line arguments (process.argv.slice(2))
 */
function runToCompletion(args: string[]): void;

Available Commands

Istanbul provides several commands accessible via the istanbul binary:

cover Command

Transparently adds coverage to Node.js command execution.

istanbul cover [options] <node-command> [-- <node-command-options>]

Purpose: Runs a Node.js command with coverage tracking enabled, automatically instrumenting required modules and generating reports.

Options:

  • --config <file> - Configuration file path (defaults to .istanbul.yml)
  • --root <path> - Root path to look for files to instrument (defaults to .)
  • -x <exclude-pattern> - One or more glob patterns to exclude (e.g. "/vendor/")
  • -i <include-pattern> - One or more glob patterns to include (e.g. "**/*.js")
  • --[no-]default-excludes - Apply default excludes [/node_modules/, /test/, /tests/] (defaults to true)
  • --hook-run-in-context - Hook vm.runInThisContext in addition to require (supports RequireJS, defaults to false)
  • --post-require-hook <file|module> - JS module that exports a function for post-require processing
  • --report <format> - Report format, can specify multiple times (defaults to lcov)
  • --dir <report-dir> - Report directory (defaults to ./coverage)
  • --print <type> - Type of report to print to console: summary (default), detail, both, or none
  • --verbose, -v - Verbose mode
  • --[no-]preserve-comments - Remove/preserve comments in output (defaults to false)
  • --include-all-sources - Instrument all unused sources after running tests (defaults to false)
  • --[no-]include-pid - Include PID in output coverage filename

Examples:

# Run tests with coverage
istanbul cover node_modules/.bin/mocha

# Run with custom options
istanbul cover --dir ./coverage --report html --report lcov node_modules/.bin/mocha

# Run Node.js script with coverage
istanbul cover -- node app.js --port 3000

# Include all source files
istanbul cover --include-all-sources node_modules/.bin/mocha

instrument Command

Instruments JavaScript files for coverage tracking.

istanbul instrument [options] <input-directory-or-file> [<output-directory>]

Purpose: Pre-instruments JavaScript files by transforming them to add coverage tracking code.

Options:

  • --config <path-to-config> - Configuration file to use (defaults to .istanbul.yml)
  • --output <file-or-dir> - Output file or directory (required when input is a directory, defaults to stdout for files)
  • -x <exclude-pattern> - One or more glob patterns to exclude (e.g. "/vendor/")
  • --variable <global-coverage-variable-name> - Change global coverage variable name from default __coverage__
  • --embed-source - Embed source code into the coverage object (defaults to false)
  • --[no-]compact - Produce [non]compact output (defaults to compact)
  • --[no-]preserve-comments - Remove/preserve comments in output (defaults to false)
  • --[no-]complete-copy - Also copy non-javascript files to output directory as is (defaults to false)
  • --save-baseline - Produce a baseline coverage.json file out of all files instrumented
  • --baseline-file <file> - Filename of baseline file (defaults to coverage/coverage-baseline.json)
  • --es-modules - Source code uses ES import/export module syntax
  • --[no-]auto-wrap - Whether to wrap code in anonymous function (defaults to true)

Examples:

# Instrument directory
istanbul instrument src/ instrumented/

# Instrument single file
istanbul instrument app.js --output instrumented/

# Instrument with options
istanbul instrument --embed-source --preserve-comments src/ build/

# Copy all files, not just JS
istanbul instrument --complete-copy src/ dist/

report Command

Generates reports from coverage JSON files.

istanbul report [options] [<report-format>...]

Purpose: Generates coverage reports in various formats from existing coverage data files.

Options:

  • --config <file> - Configuration file path
  • --dir <directory> - Output directory for reports
  • --root <directory> - Root directory for resolving file paths
  • --include <pattern> - Include file patterns
  • --exclude <pattern> - Exclude file patterns

Available Formats:

  • text - Text-based console output
  • text-summary - Summary text output
  • html - Interactive HTML report
  • lcov - LCOV format (HTML + tracefile)
  • lcovonly - LCOV tracefile only
  • json - Raw JSON coverage data
  • json-summary - JSON summary metrics
  • clover - Clover XML format
  • cobertura - Cobertura XML format
  • teamcity - TeamCity service messages

Examples:

# Generate HTML report
istanbul report html

# Generate multiple formats
istanbul report html lcov json-summary

# Generate with custom directory
istanbul report --dir ./reports html

# Generate from specific coverage files
istanbul report --dir ./reports text < coverage/coverage.json

check-coverage Command

Validates coverage against configured thresholds.

istanbul check-coverage [options]

Purpose: Checks coverage percentages against minimum thresholds and exits with error if thresholds are not met.

Options:

  • --config <file> - Configuration file path
  • --statements <percentage> - Statement coverage threshold
  • --branches <percentage> - Branch coverage threshold
  • --functions <percentage> - Function coverage threshold
  • --lines <percentage> - Line coverage threshold
  • --include <pattern> - Include file patterns
  • --exclude <pattern> - Exclude file patterns

Examples:

# Check with default thresholds from config
istanbul check-coverage

# Set custom thresholds
istanbul check-coverage --statements 90 --branches 80 --functions 95 --lines 85

# Check specific files only
istanbul check-coverage --statements 80 --include "src/**/*.js"

# Use in CI/CD pipeline
istanbul check-coverage --statements 85 --branches 75 || exit 1

help Command

Shows help information for commands.

istanbul help [command]

Examples:

# General help
istanbul help

# Command-specific help  
istanbul help cover
istanbul help instrument
istanbul help report

test Command

Runs tests with coverage using specific test frameworks.

istanbul test [options] <test-framework> [-- <test-options>]

Purpose: Runs tests using specified test framework with coverage enabled.

Supported Frameworks:

  • mocha
  • nodeunit
  • jasmine-node
  • Custom test commands

Examples:

# Run Mocha tests with coverage
istanbul test mocha

# Run with test options
istanbul test mocha -- --recursive test/

# Run custom test command
istanbul test -- node custom-test-runner.js

Configuration Files

Istanbul commands can use configuration files in YAML or JSON format:

.istanbul.yml Example:

instrumentation:
    default-excludes: true
    excludes: ['**/test/**', '**/*.test.js']
    embed-source: false
    variable: '__coverage__'
    compact: true
    preserve-comments: false
    complete-copy: false
    save-baseline: false
    include-all-sources: false
    include-pid: false

reporting:
    print: summary
    reports: ['text-summary', 'html', 'lcov']
    dir: ./coverage
    watermarks:
        statements: [50, 80]
        branches: [50, 80] 
        functions: [50, 80]
        lines: [50, 80]

hooks:
    hook-run-in-context: false
    post-require-hook: null
    handle-sigint: true

check:
    global:
        statements: 80
        branches: 75
        functions: 85
        lines: 80

Workflow Examples

Basic Test Coverage Workflow

# 1. Run tests with coverage
istanbul cover node_modules/.bin/mocha

# 2. Check coverage thresholds
istanbul check-coverage --statements 80 --branches 70

# 3. Generate additional report formats
istanbul report html lcov

Pre-instrumentation Workflow

# 1. Instrument source code
istanbul instrument src/ instrumented/

# 2. Run tests against instrumented code
NODE_PATH=instrumented npm test

# 3. Generate reports from coverage data
istanbul report html text-summary

# 4. Check thresholds
istanbul check-coverage

CI/CD Integration

#!/bin/bash
# coverage.sh - CI/CD coverage script

set -e

echo "Running tests with coverage..."
istanbul cover --include-all-sources node_modules/.bin/mocha

echo "Checking coverage thresholds..."
istanbul check-coverage \
    --statements 85 \
    --branches 75 \
    --functions 90 \
    --lines 85

echo "Generating reports..."
istanbul report html lcov json-summary

echo "Coverage analysis complete!"

Advanced Usage

Custom Configuration per Environment

# Development - detailed reporting
istanbul cover --config .istanbul.dev.yml node_modules/.bin/mocha

# CI - minimal reporting, strict thresholds  
istanbul cover --config .istanbul.ci.yml node_modules/.bin/mocha
istanbul check-coverage --config .istanbul.ci.yml

Programmatic CLI Usage

const { runToCompletion } = require('istanbul/lib/cli');

// Run CLI programmatically
try {
    runToCompletion(['cover', 'node_modules/.bin/mocha']);
    console.log('Coverage run completed successfully');
} catch (error) {
    console.error('Coverage run failed:', error.message);
    process.exit(1);
}

Integration with Build Tools

NPM Scripts

{
  "scripts": {
    "test": "mocha",
    "test:coverage": "istanbul cover node_modules/.bin/mocha",
    "coverage:check": "istanbul check-coverage --statements 80 --branches 70",
    "coverage:report": "istanbul report html",
    "coverage:all": "npm run test:coverage && npm run coverage:check && npm run coverage:report"
  }
}

Grunt Integration

// Gruntfile.js
module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-exec');
    
    grunt.initConfig({
        exec: {
            coverage: {
                cmd: 'istanbul cover node_modules/.bin/mocha'
            },
            coverage_check: {
                cmd: 'istanbul check-coverage --statements 80'
            }
        }
    });
    
    grunt.registerTask('test:coverage', ['exec:coverage', 'exec:coverage_check']);
};

Gulp Integration

// gulpfile.js
const gulp = require('gulp');
const { spawn } = require('child_process');

gulp.task('coverage', (done) => {
    const istanbul = spawn('istanbul', ['cover', 'node_modules/.bin/mocha'], {
        stdio: 'inherit'
    });
    
    istanbul.on('close', (code) => {
        if (code === 0) {
            done();
        } else {
            done(new Error(`Istanbul exited with code ${code}`));
        }
    });
});

gulp.task('coverage:check', (done) => {
    const check = spawn('istanbul', ['check-coverage', '--statements', '80'], {
        stdio: 'inherit'
    });
    
    check.on('close', (code) => {
        done(code === 0 ? null : new Error('Coverage thresholds not met'));
    });
});

Troubleshooting

Common Issues and Solutions

# Issue: Module not found errors
# Solution: Use correct paths and NODE_PATH
NODE_PATH=./instrumented istanbul cover node_modules/.bin/mocha

# Issue: ES6 modules not supported
# Solution: Enable ES modules flag
istanbul cover --es-modules node_modules/.bin/mocha

# Issue: Coverage data not found
# Solution: Ensure coverage variable is accessible
istanbul cover --variable __coverage__ node_modules/.bin/mocha

# Issue: Permission errors on output directory
# Solution: Create directory or fix permissions
mkdir -p coverage
chmod 755 coverage
istanbul cover --dir ./coverage node_modules/.bin/mocha

Debug Mode

# Enable debug output
DEBUG=istanbul:* istanbul cover node_modules/.bin/mocha

# Verbose configuration output
istanbul cover --verbose node_modules/.bin/mocha

Exit Codes

Istanbul CLI commands use standard exit codes:

  • 0 - Success
  • 1 - General error (missing files, invalid options, etc.)
  • 2 - Coverage thresholds not met (check-coverage command)
  • 3 - Configuration error
  • 4 - Instrumentation error

Example Exit Code Handling:

#!/bin/bash
istanbul check-coverage --statements 80 --branches 70
EXIT_CODE=$?

case $EXIT_CODE in
    0)
        echo "Coverage thresholds met"
        ;;
    2)
        echo "Coverage thresholds not met"
        exit 1
        ;;
    *)
        echo "Coverage check failed with code $EXIT_CODE"
        exit $EXIT_CODE
        ;;
esac

docs

cli.md

collection.md

configuration.md

hooks.md

index.md

instrumentation.md

reporting.md

storage.md

tree-summarizer.md

utilities.md

tile.json