Comprehensive JavaScript code coverage tool that computes statement, line, function and branch coverage with module loader hooks for transparent instrumentation
npx @tessl/cli install tessl/npm-istanbul@0.4.0Istanbul is a comprehensive JavaScript code coverage tool that computes statement, line, function and branch coverage with module loader hooks to transparently add coverage when running tests. It supports all JS coverage use cases including unit tests, server side functional tests and browser tests, built for scale.
npm install istanbulconst istanbul = require('istanbul');
const { Instrumenter, Collector, Reporter } = require('istanbul');For ES modules (if supported by your environment):
import istanbul from 'istanbul';
import { Instrumenter, Collector, Reporter } from 'istanbul';const fs = require('fs');
const istanbul = require('istanbul');
// Create instrumenter
const instrumenter = new istanbul.Instrumenter();
// Instrument some code
const code = fs.readFileSync('myScript.js', 'utf8');
const instrumentedCode = instrumenter.instrumentSync(code, 'myScript.js');
// Run the instrumented code (this will populate global.__coverage__)
eval(instrumentedCode);
// Collect coverage data
const collector = new istanbul.Collector();
collector.add(global.__coverage__);
// Generate reports
const reporter = new istanbul.Reporter();
reporter.addAll(['text', 'lcov', 'html']);
reporter.write(collector, true, () => {
console.log('Coverage reports generated!');
});Istanbul is built around several key components:
Transform JavaScript code to track statement, line, function, and branch coverage during execution.
class Instrumenter {
constructor(options?: InstrumentOptions);
instrumentSync(code: string, filename: string): string;
instrument(code: string, filename: string, callback: (err: Error, code: string) => void): void;
lastFileCoverage(): Object;
}
interface InstrumentOptions {
coverageVariable?: string;
embedSource?: boolean;
preserveComments?: boolean;
noCompact?: boolean;
esModules?: boolean;
noAutoWrap?: boolean;
codeGenerationOptions?: Object;
debug?: boolean;
walkDebug?: boolean;
}Merge and process coverage data from multiple sources and test runs.
class Collector {
constructor(options?: CollectorOptions);
add(coverage: Object, testName?: string): void;
files(): string[];
fileCoverageFor(fileName: string): Object;
getFinalCoverage(): Object;
dispose(): void;
}
interface CollectorOptions {
store?: Store;
}Generate coverage reports in various formats including HTML, LCOV, text, and JSON.
class Reporter {
constructor(cfg?: Configuration, dir?: string);
add(fmt: string): void;
addAll(fmts: string[]): void;
write(collector: Collector, sync: boolean, callback?: () => void): void;
}
class Report {
static create(type: string, opts?: Object): Report;
static getReportList(): string[];
writeReport(collector: Collector, sync?: boolean): void;
}Hook into Node.js module loading system to instrument code transparently at runtime.
const hook = {
hookRequire(matcher: Function, transformer: Function, options?: Object): void;
unhookRequire(): void;
hookCreateScript(matcher: Function, transformer: Function, opts?: Object): void;
unhookCreateScript(): void;
hookRunInThisContext(matcher: Function, transformer: Function, opts?: Object): void;
unhookRunInThisContext(): void;
unloadRequireCache(matcher: Function): void;
};Load and manage Istanbul configuration from files or objects with validation and defaults.
const config = {
loadFile(file: string, overrides?: Object): Configuration;
loadObject(obj: Object, overrides?: Object): Configuration;
defaultConfig(): Object;
};
class Configuration {
constructor(obj: Object, overrides?: Object);
instrumentation: InstrumentationOptions;
reporting: ReportingOptions;
hooks: HookOptions;
}Pluggable storage backends for coverage data with memory, filesystem, and temporary storage options.
class Store {
static create(type: string, opts?: Object): Store;
static register(constructor: Function): void;
set(key: string, contents: string): void;
get(key: string): string;
keys(): string[];
hasKey(key: string): boolean;
dispose(): void;
getObject(key: string): Object;
setObject(key: string, object: Object): void;
}Process and manipulate coverage objects including merging, summarization, and format conversion.
const utils = {
addDerivedInfo(coverage: Object): void;
addDerivedInfoForFile(fileCoverage: Object): void;
removeDerivedInfo(coverage: Object): void;
blankSummary(): Object;
summarizeFileCoverage(fileCoverage: Object): Object;
summarizeCoverage(coverage: Object): Object;
mergeFileCoverage(first: Object, second: Object): Object;
mergeSummaryObjects(...summaries: Object[]): Object;
};Generate hierarchical coverage summaries organized by directory structure for comprehensive coverage analysis and HTML report generation.
class TreeSummarizer {
constructor();
addFileCoverageSummary(filePath: string, metrics: Object): void;
getTreeSummary(): TreeSummary;
}
interface TreeSummary {
prefix: string[];
root: Node;
getNode(shortName: string): Node;
toJSON(): Object;
}
interface Node {
name: string;
relativeName: string;
fullName: string;
kind: 'file' | 'dir';
metrics: Object | null;
packageMetrics: Object | null;
parent: Node | null;
children: Node[];
displayShortName(): string;
addChild(child: Node): void;
toJSON(): Object;
}Complete command-line tools for instrumenting code, running tests with coverage, and generating reports.
Available commands:
istanbul cover - Run commands with coverageistanbul instrument - Instrument JavaScript filesistanbul report - Generate reports from coverage dataistanbul check-coverage - Validate coverage thresholdsistanbul test - Run tests with coverageistanbul help - Show command help// Main module exports
const istanbul = {
Instrumenter: Instrumenter,
Store: Store,
Collector: Collector,
hook: hook,
Report: Report,
config: config,
Reporter: Reporter,
utils: utils,
matcherFor: Function,
VERSION: string,
Writer: Writer,
ContentWriter: ContentWriter,
FileWriter: FileWriter,
TreeSummarizer: TreeSummarizer,
assetsDir: string,
_yuiLoadHook: Object // Internal YUI loading support (undocumented)
};