- Notifications
You must be signed in to change notification settings - Fork359
the Istanbul command line interface
License
istanbuljs/nyc
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Having problems? want to contribute? join ourcommunity slack.
Istanbul's state of the art command line interface, with support for:
- applications that spawn subprocesses.
- source mapped coverage of Babel and TypeScript projects
Istanbul instruments your ES5 and ES2015+ JavaScript code with line counters, so that you can track how well your unit-tests exercise your codebase.
Thenyc
command-line-client for Istanbul works well with most JavaScript testing frameworks: tap, mocha, AVA, etc.
Use your package manager to add it as a dev dependency:npm i -D nyc
oryarn add -D nyc
.You can use nyc to call npm scripts (assuming they don't already have nyc executed in them), like so (replacemocha
with your test runner everywhere you see it):
{"scripts": {"test":"mocha","coverage":"nyc npm run test" }}
You can use alsonpx
instead of installing nyc as a dependency, but you might get updates you are not ready for; to get around this, pin to a specific major version by specifying, e.g.nyc@14
.
{"scripts": {"test":"npx nyc@latest mocha" }}
This is a good way of testing upcoming releases of nyc, usually on thenext
tag.
Note: If you usejest
ortap
, you do not need to installnyc
.Those runners already have the IstanbulJS libraries to provide coverage for you.Follow their documentation to enable and configure coverage reporting.
nyc accepts a wide variety of configuration arguments, runnpx nyc --help
for thorough documentation.
Configuration arguments on the command-line should be provided prior to the program that nyc is executing.As an example, the following command executesava
, and indicates to nyc that it should output both anlcov
(lcov.info
+ html report) and atext-summary
coverage report.
nyc --reporter=lcov --reporter=text-summary ava
Please start with the pre-configured@istanbuljs/nyc-config-babel
preset.You can add your custom configuration options as shown below.
Please start with the pre-configured@istanbuljs/nyc-config-typescript
preset.
nyc allows you to inherit other configurations using the keyextends
in thepackage.json
stanza,.nycrc
, or YAML files.You can then add the specific configuration options you want that aren't in that particular shared config, e.g.
{"extends":"@istanbuljs/nyc-config-typescript","all":true,"check-coverage":true}
Any configuration options that can be set via the command line can also be specified in thenyc
stanza of your package.json, or within a separate configuration file - a variety of flavors are available:
File name | File Association |
---|---|
.nycrc | JSON |
.nycrc.json | JSON |
.nycrc.yaml | YAML |
.nycrc.yml | YAML |
nyc.config.js | CommonJS export |
Seenyc --help
for all options available.You can set these in any of the files listed above, or from the command line.This table is a quick TLDR for the rest of this readme and there are more advanced docs available.
Option name | Description | Type | Default |
---|---|---|---|
all | Whether or not to instrument all files (not just the ones touched by your test suite) | Boolean | false |
check-coverage | Check whether coverage is within thresholds, fail if not | Boolean | false |
extension | List of extensions that nyc should attempt to handle in addition to.js | Array<String> | ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx'] |
include | Seeselecting files for coverage for more info | Array<String> | ['**'] |
exclude | Seeselecting files for coverage for more info | Array<String> | list |
reporter | May be set to abuilt-in coverage reporter or an npm package (dev)dependency | Array<String> | ['text'] |
report-dir | Where to put the coverage report files | String | ./coverage |
skip-full | Don't show files with 100% statement, branch, and function coverage | Boolean | false |
temp-dir | Directory to output raw coverage information to | String | ./.nyc_output |
Configuration can also be provided bynyc.config.js
if programmed logic is required:
'use strict';constdefaultExclude=require('@istanbuljs/schema/default-exclude');constisWindows=require('is-windows');letplatformExclude=[isWindows() ?'lib/posix.js' :'lib/win32.js'];module.exports={exclude:platformExclude.concat(defaultExclude)};
To publish and reuse your ownnyc
configuration, simply create an npm module that exports your JSON config (viaindex.json
or a CJSindex.js
).
A more advanced use case would be to combine multiple shared configs in anyc.config.js
file:
'use strict';constbabelConfig=require('@istanbuljs/nyc-config-babel');consthookRunInThisContextConfig=require('@istanbuljs/nyc-config-hook-run-in-this-context');module.exports={ ...babelConfig, ...hookRunInThisContextConfig,all:true,'check-coverage':true};
By default, nyc only collects coverage for source files that are visited during a test.It does this by watching for files that arerequire()
'd during the test.When a file isrequire()
'd, nyc creates and returns an instrumented version of the source, rather than the original.Only source files that are visited during a test will appear in the coverage report and contribute to coverage statistics.
nyc will instrument all files if the--all
flag is set or if runningnyc instrument
.In this case all files will appear in the coverage report and contribute to coverage statistics.
nyc will only collect coverage for files that are located undercwd
, and then only files with extensions listed in theextension
array.
You can reduce the set of instrumented files by addinginclude
andexclude
filter arrays to your config.These allow you to shape the set of instrumented files by specifying glob patterns that can filter files from the default instrumented set.Theexclude
array may also use exclude negated glob patterns, these are specified with a!
prefix, and can restore sub-paths of excluded paths.
Globs are matched usingminimatch.
We use the following process to remove files from consideration:
- Limit the set of instrumented files to those files in paths listed in the
include
array. - Remove any files that are found in the
exclude
array. - Restore any exclude negated files that have been excluded in step 2.
If there are paths specified in theinclude
array, then the set of instrumented files will be limited to eligible files found in those paths.If theinclude
array is left undefined all eligible files will be included, equivalent to settinginclude: ['**']
.Multipleinclude
globs can be specified on the command line, each must follow a--include
,-n
switch.
If there are paths specified in theexclude
array, then the set of instrumented files will not feature eligible files found in those paths.You can also specify negated paths in theexclude
array, by prefixing them with a!
.Negated paths can restore paths that have been already been excluded in theexclude
array.Multipleexclude
globs can be specified on the command line, each must follow a--exclude
,-x
switch.
The defaultexclude
list is defined in the@istanbuljs/schema module.Specifying your own exclude property completely replaces these defaults.
For example, the followingnyc
config will collect coverage for every file in thesrc
directory regardless of whether it isrequire()
'd in a test.It will also exclude any files with the extension.spec.js
.
{"all":true,"include": ["src/**/*.js" ],"exclude": ["**/*.spec.js" ]}
Note: Be wary of automatic OS glob expansion when specifying include/exclude globs with the CLI.To prevent this, wrap each glob in single quotes.
We always add**/node_modules/**
to the exclude list, even if not specified in the config.You can override this by setting--exclude-node-modules=false
.
For example,"excludeNodeModules: false"
in the followingnyc
config will preventnode_modules
from being added to the exclude rules.The set of include rules then restrict nyc to only consider instrumenting files found under thelib/
andnode_modules/@my-org/
directories.The exclude rules then prevent nyc instrumenting anything in atest
folder and the filenode_modules/@my-org/something/unwanted.js
.
{"all":true,"include": ["lib/**","node_modules/@my-org/**" ],"exclude": ["node_modules/@my-org/something/unwanted.js","**/test/**" ],"excludeNodeModules":false}
nyc runs a lot of file system operations relative to the project root directory.During startup nyc will look for thedefault project root directory.Thedefault project root directory is the first directory found that contains apackage.json
file when searching from the current working directory up.If nyc fails to find a directory containing apackage.json
file, it will use the current working directory as thedefault project root directory.You can change the project root directory with the--cwd
option.
nyc uses the project root directory when:
- looking for source files to instrument
- creating globs for include and exclude rules during file selection
- loading custom require hooks from the
require
array
nyc may create artifact directories within the project root, with these defaults:
- the report directory,
<project-root>/coverage
- the cache directory,
<project-root>/node_modules/.cache/nyc
- the temp directory,
<project-root>/.nyc_output
The--require
flag can be provided tonyc
to indicate that additional modules should be required in the subprocess collecting coverage:
nyc --require esm mocha
The--require
flag also operates on the main nyc process for use by--all
.For example, in situations withnyc --all --instrument false
andbabel-plugin-istanbul
setup the--all
option only works if--require @babel/register
is passed to nyc.Passing it to mocha would cause the tests to be instrumented but unloaded sources would not be seen.The@istanbuljs/nyc-config-babel
package handles this for you!
nyc
's default behavior is to cache instrumented files to disk to prevent instrumenting source files multiple times, and speednyc
execution times.You can disable this behavior by runningnyc
with the--cache false
flag.You can also change the default cache directory from./node_modules/.cache/nyc
by setting the--cache-dir
flag.
You can set custom coverage thresholds that will fail ifcheck-coverage
is set totrue
and your coverage drops below those thresholds.For example, in the followingnyc
configuration, dropping below 80% branch, line, functions, or statements coverage would fail the build (you can have any combination of these):
{"branches":80,"lines":80,"functions":80,"statements":80}
To do this check on a per-file basis (as opposed to in aggregate), set theper-file
option totrue
.
Several of the coverage reporters supported by nyc display special information for high and low watermarks:
- high-watermarks represent healthy test coverage (in many reports this is represented with green highlighting).
- low-watermarks represent sub-optimal coverage levels (in many reports this is represented with red highlighting).
You can specify custom high and low watermarks in nyc's configuration:
{"watermarks": {"lines": [80,95],"functions": [80,95],"branches": [80,95],"statements": [80,95] }}
There may be some sections of your codebase that you wish to purposefullyexclude from coverage tracking, to do so you can use the following parsinghints:
/* istanbul ignore if */
: ignore the next if statement./* istanbul ignore else */
: ignore the else portion of an if statement./* istanbul ignore next */
: ignore the nextthing in the source-code (functions, if statements, classes, you name it)./* istanbul ignore file */
: ignore an entire source-file (this should beplaced at the top of the file).
You can ignore every instance of a method simply by adding its name to theignore-class-method
array in yournyc
config.
{"ignore-class-method": ["render"]}
If for whatever reason you have different test runners in your project or a different series of test runs for different kinds of tests, nyc will automatically combine the coverage report for you if configured correctly with the--no-clean
flag and thereport
command.Originally inspired by @janiukjf in #1001, here's an example, where thetest:*
scripts (not shown) invoke only your test runner(s) and not nyc:
{"scripts": {"cover":"npm run cover:unit && npm run cover:integration && npm run cover:report","cover:unit":"nyc --silent npm run test:unit","cover:integration":"nyc --silent --no-clean npm run test:integration","cover:report":"nyc report --reporter=lcov --reporter=text" }}
Thenyc merge
command is for producing oneraw coverage output file that combines the results from many test runs.So if you had the above setup and needed to produce a singlecoverage.json
for some external tool, you could do:
{"scripts": {"cover:merge":"npm run cover:unit && npm run cover:integration && nyc merge .nyc_output coverage.json" }}
If you opt to pre-instrument your source-code (rather than using a just-in-time transpiler like@babel/register
) nyc supports both inline source-maps and.map
files.
Important: If you are using nyc with a project that pre-instruments its code, run nyc with the configuration option--exclude-after-remap
set tofalse
.Otherwise nyc's reports will exclude any files that source-maps remap to folders covered under exclude rules.
Many testing frameworks (Mocha, Tape, Tap, etc.) can produceTAP output.tap-nyc is a TAP formatter designed to look nice with nyc.
Seemore nyc tutorials andadvanced nyc documentation.
Please feel free tocontribute documentation to help us improve.
Available as part of the Tidelift Subscription.
The maintainers ofnyc
and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.Learn more.
About
the Istanbul command line interface