Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

istanbul

gotwarlost2.1mBSD-3-Clausedeprecated0.4.5TypeScript support: definitely-typed

This module is no longer maintained, try this instead: npm i nyc Visit https://istanbul.js.org/integrations for other alternatives.

Yet another JS code coverage tool that computes statement, line, function and branch coverage with module loader hooks to transparently add coverage when running tests. Supports all JS coverage use cases including unit tests, server side functional tests

coverage, code coverage, JS code coverage, JS coverage

readme

Istanbul - a JS code coverage tool written in JS

Build Status Dependency Status Coverage Status bitHound Score

NPM

New v0.4.0 now has beautiful HTML reports. Props to Tom MacWright @tmcw for a fantastic job!

Features

  • All-javascript instrumentation library that tracks statement, branch, and function coverage.
  • Module loader hooks to instrument code on the fly
  • Command line tools to run node unit tests "with coverage turned on" and no cooperation whatsoever from the test runner
  • Multiple report formats: HTML, LCOV, Cobertura and more.
  • Ability to use as middleware when serving JS files that need to be tested on the browser.
  • Can be used on the command line as well as a library
  • Based on the awesome esprima parser and the equally awesome escodegen code generator
  • Well-tested on node (prev, current and next versions) and the browser (instrumentation library only)

Use cases

Supports the following use cases and more

  • transparent coverage of nodejs unit tests
  • instrumentation/ reporting of files in batch mode for browser tests
  • Server side code coverage for nodejs by embedding it as custom middleware

Getting started

$ npm install -g istanbul

The best way to see it in action is to run node unit tests. Say you have a test script test.js that runs all tests for your node project without coverage.

Simply:

$ cd /path/to/your/source/root
$ istanbul cover test.js

and this should produce a coverage.json, lcov.info and lcov-report/*html under ./coverage

Sample of code coverage reports produced by this tool (for this tool!):

HTML reports

Usage on Windows

Istanbul assumes that the command passed to it is a JS file (e.g. Jasmine, vows etc.), this is however not true on Windows where npm wrap bin files in a .cmd file. Since Istanbul can not parse .cmd files you need to reference the bin file manually.

Here is an example using Jasmine 2:

istanbul cover node_modules\jasmine\bin\jasmine.js

In order to use this cross platform (e.i. Linux, Mac and Windows), you can insert the above line into the script object in your package.json file but with normal slash.

"scripts": {
    "test": "istanbul cover node_modules/jasmine/bin/jasmine.js"
}

Configuring

Drop a .istanbul.yml file at the top of the source tree to configure istanbul. istanbul help config tells you more about the config file format.

The command line

$ istanbul help

gives you detailed help on all commands.

Usage: istanbul help config | <command>

`config` provides help with istanbul configuration

Available commands are:

      check-coverage
              checks overall/per-file coverage against thresholds from coverage
              JSON files. Exits 1 if thresholds are not met, 0 otherwise


      cover   transparently adds coverage information to a node command. Saves
              coverage.json and reports at the end of execution


      help    shows help


      instrument
              instruments a file or a directory tree and writes the
              instrumented code to the desired output location


      report  writes reports for coverage JSON objects produced in a previous
              run


      test    cover a node command only when npm_config_coverage is set. Use in
              an `npm test` script for conditional coverage


Command names can be abbreviated as long as the abbreviation is unambiguous

To get detailed help for a command and what command-line options it supports, run:

istanbul help <command>

(Most of the command line options are not covered in this document.)

The cover command

$ istanbul cover my-test-script.js -- my test args
# note the -- between the command name and the arguments to be passed

The cover command can be used to get a coverage object and reports for any arbitrary node script. By default, coverage information is written under ./coverage - this can be changed using command-line options.

The cover command can also be passed an optional --handle-sigint flag to enable writing reports when a user triggers a manual SIGINT of the process that is being covered. This can be useful when you are generating coverage for a long lived process.

The test command

The test command has almost the same behavior as the cover command, except that it skips coverage unless the npm_config_coverage environment variable is set.

This command is deprecated since the latest versions of npm do not seem to set the npm_config_coverage variable.

The instrument command

Instruments a single JS file or an entire directory tree and produces an output directory tree with instrumented code. This should not be required for running node unit tests but is useful for tests to be run on the browser.

The report command

Writes reports using coverage*.json files as the source of coverage information. Reports are available in multiple formats and can be individually configured using the istanbul config file. See istanbul help report for more details.

The check-coverage command

Checks the coverage of statements, functions, branches, and lines against the provided thresholds. Positive thresholds are taken to be the minimum percentage required and negative numbers are taken to be the number of uncovered entities allowed.

Ignoring code for coverage

  • Skip an if or else path with /* istanbul ignore if */ or /* istanbul ignore else */ respectively.
  • For all other cases, skip the next 'thing' in the source with: /* istanbul ignore next */

See ignoring-code-for-coverage.md for the spec.

API

All the features of istanbul can be accessed as a library.

Instrument code

    var istanbul = require('istanbul');
    var instrumenter = new istanbul.Instrumenter();

    var generatedCode = instrumenter.instrumentSync('function meaningOfLife() { return 42; }',
        'filename.js');

Generate reports given a bunch of coverage JSON objects

    var istanbul = require('istanbul'),
        collector = new istanbul.Collector(),
        reporter = new istanbul.Reporter(),
        sync = false;

    collector.add(obj1);
    collector.add(obj2); //etc.

    reporter.add('text');
    reporter.addAll([ 'lcov', 'clover' ]);
    reporter.write(collector, sync, function () {
        console.log('All reports generated');
    });

For the gory details consult the public API

Multiple Process Usage

Istanbul can be used in a multiple process environment by running each process with Istanbul, writing a unique coverage file for each process, and combining the results when generating reports. The method used to perform this will depend on the process forking API used. For example when using the cluster module you must setup the master to start child processes with Istanbul coverage, disable reporting, and output coverage files that include the PID in the filename. Before each run you may need to clear out the coverage data directory.

    if(cluster.isMaster) {
        // setup cluster if running with istanbul coverage
        if(process.env.running_under_istanbul) {
            // use coverage for forked process
            // disabled reporting and output for child process
            // enable pid in child process coverage filename
            cluster.setupMaster({
                exec: './node_modules/.bin/istanbul',
                args: [
                    'cover', '--report', 'none', '--print', 'none', '--include-pid',
                    process.argv[1], '--'].concat(process.argv.slice(2))
            });
        }
        // ...
        // ... cluster.fork();
        // ...
    } else {
        // ... worker code
    }

Coverage.json

For details on the format of the coverage.json object, see here.

License

istanbul is licensed under the BSD License.

Third-party libraries

The following third-party libraries are used by this module:

Inspired by

  • YUI test coverage - https://github.com/yui/yuitest - the grand-daddy of JS coverage tools. Istanbul has been specifically designed to offer an alternative to this library with an easy migration path.
  • cover: https://github.com/itay/node-cover - the inspiration for the cover command, modeled after the run command in that tool. The coverage methodology used by istanbul is quite different, however

Shout out to

  • mfncooper - for great brainstorming discussions
  • reid, davglass, the YUI dudes, for interesting conversations, encouragement, support and gentle pressure to get it done :)

Why the funky name?

Since all the good ones are taken. Comes from the loose association of ideas across coverage, carpet-area coverage, the country that makes good carpets and so on...

changelog

Changelog

0.4.5
  • log filename when file fails to parse using esprima, thanks to @djorg83
  • swap fileset for glob (security fix), thanks to @popomore and @graingert
0.4.4
  • Handle ExportNamedDeclaration, thanks to @VictoryStick
  • Use tmpdir setting in temp store, thanks to @inversion
  • Set "medium" coverage CSS color scheme to yellow, thanks to @JamesMGreene
  • use os.tmpdir() instead of os.tmpDir(), thanks to @ChALkeR
0.4.3
  • Create new handlebars instance for the HTML report, thanks to @doowb
  • MetaProperty support thanks to @steve-gray
  • Use ansi colors from 16-color palette for better console support, thanks to @jtangelder
  • Misc doc/ css fixes thanks to @pra85, @abejfehr
0.4.2 Fix confusing error message on check-coverage failures, thanks to @isaacs/td>
v0.4.1
  • Update esprima to 2.7.x, thanks to @ariya
  • Make table header clickable in HTML report, thanks to @iphands
  • Fix strict mode issues thanks to @kpdecker
  • update ignore code example for UMD, thanks to @pgurnee
  • misc build fixes, no user visible changes, thanks to @ariya
v0.4.0
  • HTML report design, thanks a bunch to @tmcw
  • "loading config file" message on the console is now tied to the verbose state, thanks @asa-git
  • Add the `l` property to documentation, thanks @kitsonk
  • </ul>
v0.3.21
  • Updated dependencies to the latest
v0.3.20
  • Fix broken es6 `super` support, thanks @sterlinghw
  • Improve readability via better lineHeight, thanks @dhoko
  • Adding ability to set custom block name in teamcity report, thanks @aryelu
  • Replaced deprecated util.puts with console.log, thanks @arty-name
v0.3.19 Fix instrumenter for multiple blank array positions, thanks @alexdunphy
v0.3.18 Upgrade esprima, get support for more ES6 features
v0.3.17 Upgrade esprima, get correct for-of support
v0.3.16
  • upgrades to filset and async modules, thanks to @roderickhsiao, @popomore
  • updated text reporter so that it displays a list of the lines missing coverage, thanks @bcoe
v0.3.15
  • Fix #375: add nodir option to exclude directory for *.js matcher thanks to @yurenju
  • Fix #362: When setting up the `reportDir` add it to `reporter.dir`
  • Fixes #238 (added a poorman's clone)
  • Incrementing hits on ignored statements implemented
  • `a:visited color: #777` (a nice gray color)
v0.3.14 Add text-lcov report format to emit lcov to console, thanks to @bcoe
v0.3.13 Fix #339
v0.3.12 Allow other-than-dot-js files to be hooked, thanks to @sethpollack
v0.3.11 Avoid modification of global objects, thanks to @dominykas
v0.3.10 Update escodegen to 1.6.x and add browser download script
v0.3.9
  • Merge harmony branch and start adding ES6 features to istanbul
  • Arrow functions are the only feature of interest now
  • `for-of` and `yield` support exist but not present in mainline esprima yet
v0.3.8
  • Fail check coverage command when no coverage files found, thanks to @nexus-uw
  • handle relative paths in check-coverage, thanks to @dragn
  • support explicit includes for cover, thanks to @tonylukasavage
v0.3.7 Fix asset paths on windows, thanks to @juangabreil
v0.3.6
  • Update to Esprima 2.0
  • Remove YUI dependency and provide custom sort code. No network access needed for HTML report view
  • use supports-color module to colorize output, thanks to @gustavnikolaj
  • Fix tests to work on Windows, thanks to @dougwilson
  • Docs: "Instrument code" API example correction thanks to @robatron
  • Extracted embedded CSS and JavaScript and made them external files, thanks to @booleangate
v0.3.5

Merge #275 - `--include-all-sources` option. Thanks @gustavnikolaj

The `--preload-sources` option is now deprecated and superseded by the `--include-all-sources` option instead. This provides a better coverage representation of the code that has not been included for testing.

v0.3.4 Merge #219 - Support reporting within symlink/junction. Thanks to @dougwilson
v0.3.3 Merge #268 - per file coverage enforcement. Thanks to @ryan-roemer
v0.3.2 Republish 0.3.1 because of bad shasum
v0.3.1 Fixes #249
v0.3.0 The *reports* release. **Potentially backwards-incompatible** if you are using undocumented features or custom report implementations.
  • Change report command line to support multiple reports, add back-compat processing with warnings
  • Enable `report` command to read report list from config, thanks to @piuccio
  • Support multiple reports for `cover` and `report` commands
  • Support per-report config options in configuration file
  • Turn reports into event emitters so they can signal `done`
  • Add `Reporter` class to be able to generate multiple reports
  • Add a bunch of API docs, refactor README
v0.2.16Make YUI links https-always since relative links break local filesystem use-case
v0.2.15make link protocols relative so they don't break on https connections (thanks to @yasyf)
v0.2.14Fix hook to deal with non-string/ missing filenames (thanks to @jason0x43), update dependencies
v0.2.13Add `--preload-sources` option to `cover` command to make code not required by tests to appear in the coverage report.
v0.2.12Text summary as valid markdown, thanks to @smikes
v0.2.11Allow source map generation, thanks to @jason0x43
v0.2.10Add flag to handle sigints and dump coverage, thanks to @samccone
v0.2.9Fix #202
v0.2.8Upgrade esprima
v0.2.7
  • Upgrade esprima
  • Misc jshint fixes
v0.2.6
  • Revert bad commit for tree summarizer
v0.2.5
  • Add clover report, thanks to @bixdeng, @mpderbec
  • Fix cobertura report bug for relative paths, thanks to @jxiaodev
  • Run self-coverage on tests always
  • Fix tree summarizer when relative paths are involved, thanks to @Swatinem
v0.2.4
  • Fix line-split algo to handle Mac lin separators, thanks to @asifrc
  • Update README for quick intro to ignoring code for coverage, thanks to @gergelyke
v0.2.3
  • Add YAML config file. `istanbul help config` has more details
  • Support custom reporting thresholds using the `watermarks` section of the config file
v0.2.2update escodegen, handlebars and resolve dependency versions
v0.2.1
  • Add ability to skip branches and other hard-to-test code using comments. See the doc for more details
  • Turn `util.error` into `console.error` for node 0.11 compatibility, thanks to @pornel
v0.2.0
  • Add --preserve-comments to instrumenter options, thanks to @arikon
  • Support 'use strict;' in file scope, thanks to @pornel
Up minor version due to the new way in which the global object is accessed. This _should_ be backwards-compatible but has not been tested in the wild.
v0.1.46Fix #114
v0.1.45Add teamcity reporter, thanks to @chrisgladd
v0.1.44Fix inconsistency in processing empty switch with latest esprima, up deps
v0.1.43Add colors to text report thanks to @runk
v0.1.42fix #78: embed source regression introduced in v0.1.38. Fix broken test for this
v0.1.41add json report to dump coverage object for certain use cases
v0.1.40forward sourceStore from lcov to html report, pull request by @vojtajina
v0.1.39add <source> tag to cobertura report, pull request by @jhansche
v0.1.38
  • factor out AST instrumentation into own instrumentASTSync method
  • always set function declaration coverage stats to 1 since every such declaration is "executed" exactly one time by the compiler
v0.1.37--complete-copy flag contrib from @kami, correct strict mode semantics for instrumented functions
v0.1.36real quiet when --print=none specified, add repo URL to package.json, add contributors
v0.1.35accept cobertura contrib from @nbrownus, fix #52
v0.1.34fix async reporting, update dependencies, accept html cleanup contrib from @mathiasbynens
v0.1.33initialize global coverage object before running tests to workaround mocha leak detection
v0.1.32Fix for null nodes in array expressions, add @unindented as contributor
v0.1.31Misc internal fixes and test changes
v0.1.30Write standard blurbs ("writing coverage object..." etc.) to stderr rather than stdout
v0.1.29Allow --post-require-hook to be a module that can be `require`-d
v0.1.28Add --post-require-hook switch to support use-cases similar to the YUI loader
v0.1.27Add --hook-run-in-context switch to support RequireJS modules. Thanks to @millermedeiros for the pull request
v0.1.26Add support for minimum uncovered unit for check-coverage. Fixes #25
v0.1.25Allow for relative paths in the YUI loader hook
v0.1.24Add lcov summaries. Fixes issue #20
v0.1.23Add ability to save a baseline coverage file for the instrument command. Fixes issue #19
v0.1.22Add signature attribute to cobertura method tags to fix NPE by the Hudson publisher
v0.1.21Add cobertura XML report format; exprimental for now
v0.1.20Fix HTML/ lcov report interface to be more customizable for middleware needs
v0.1.19make all hooking non-destructive in that already loaded modules are never reloaded. Add self-test mode so that already loaded istanbul modules can be unloaded prior to hooking.
v0.1.18Add option to hook in non-destructive mode; i.e. the require cache is not unloaded when hooking
v0.1.17Export some more objects; undocumented for now
v0.1.16Fix npm keywords for istanbul which expects an array of strings but was being fed a single string with keywords instead
v0.1.15Add the 'check-coverage' command so that Istanbul can be used as a posttest script to enforce minimum coverage
v0.1.14Expose the experimental YUI load hook in the interface
v0.1.13Internal jshint cleanup, no features or fixes
v0.1.12Give npm the README that was getting inadvertently excluded
v0.1.11Merge pull request #14 for HTML tweaks. Thanks @davglass. Add @davglass and @nowamasa as contributors in `package.json`
v0.1.10Fix to issue #12. Do not install `uncaughtException` handler and pass input error back to CLI using a callback as opposed to throwing.
v0.1.9Attempt to create reporting directory again just before writing coverage in addition to initial creation
v0.1.8Fix issue #11.
v0.1.7Add text summary and detailed reporting available as --print [summary|detail|both|none]. summary is the default if nothing specified.
v0.1.6Handle backslashes in the file path correctly in emitted code. Fixes #9. Thanks to @nowamasa for bug report and fix
v0.1.5make object-utils.js work on a browser as-is
v0.1.4partial fix for issue #4; add titles to missing coverage spans, remove negative margin for missing if/else indicators
v0.1.3Set the environment variable running_under_istanbul to 1 when that is the case. This allows test runners that use istanbul as a library to back off on using it when set.
v0.1.2HTML reporting cosmetics. Reports now show syntax-colored JS using `prettify`. Summary tables no longer wrap in awkward places.
v0.1.1Fixes issue #1. HTML reports use sources embedded inside the file coverage objects if found rather than reading from the filesystem
v0.1.0Initial version