Now (2021) the preferred way to use istanbul is via its "state of the art command line interface" nyc.
First, install it in your project with
npm i nyc --save-dev
Then, if you have a npm based project, just change the test script inside the scripts
object of your package.json file to execute code coverage of your mocha tests:
{
"scripts": {
"test": "nyc --reporter=text mocha"
}
}
Now run your tests
npm test
and you will see a table like this in your console, just after your tests output:
Just use
nyc --reporter=html
instead of text
. Now it will produce a report inside ./coverage/index.html
.
Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you.
Just add a --reporter=REPORTER_NAME
option for each format you want.
For example, with
nyc --reporter=html --reporter=text
you will have both the console and the html report.
Just add another script in your package.json
and leave the test
script with only your test runner (e.g. mocha):
{
"scripts": {
"test": "mocha",
"test-with-coverage": "nyc --reporter=text mocha"
}
}
Now run this custom script
npm run test-with-coverage
to run tests with code coverage.
Fail if the total code coverage is below 90%:
nyc --check-coverage --lines 90
Fail if the code coverage of at least one file is below 90%:
nyc --check-coverage --lines 90 --per-file