Say that you have a bunch of Typescript projects that also have a bunch of unit tests per project. Now you want to go one step further, you want to know what is the coverage of those tests.
In simple terms, test coverage measures the percent of your codebase that is being covered by tests, so the higher the coverage the safer your code is (assuming that the tests were properly coded).
To start, you will need to install Istanbum command line interface (package nyc) and its pre-configuration for typescript projects (package @istanbuljs/nyc-config-typescript) by running this command:
$ npm install --save-dev nyc \
@istanbuljs/nyc-config-typescript
Once installed, create a nyc configuration file called .nycrc
(optionally you can use the .json
extension and call it .nycrc.json
) with this content:
// .nycrc file
{
"extends": "@istanbuljs/nyc-config-typescript"
}
Finally, and assuming you had a script called test
in your package.json
file, create a new script called coverage
with this content:
// package.json file
{
...
"scripts": {
...
"coverage": "nyc npm run test"
}
}
To check that everything is correct, run the new script (npm run coverage
) and you should see your tests being executed and, after them, a coverage report being printed in the console.
Understanding the coverage report
The coverage report shows the percent of the code being covered by the tests from four different perspectives:
- The statements being covered (
% Stmts
) - The branches being covered (
% Branch
), meaning a branch every code bifurcation as when you use a if statement. - The functions being covered (
% Funcs
) - The lines of code being covered (
% Lines
)
More importantly, the coverage report also states specifically what lines or each file are not covered by tests (Uncovered Line #s
).
Checking the coverage values
nyc
support the possibility of checking that certain coverage metrics are above certain limits and, in case of being below, triggering an error. This is useful if you are applying coverage checks in a pre-commit process, therefore avoiding commiting code that did not match a certain quality degree.
To state coverage checks, set the .nycrc
(or .nycrc.json
) configuration file in this way:
// .nycrc file
{
"extends": "@istanbuljs/nyc-config-typescript",
"check-coverage": true,
"branches": 70,
"lines": 70,
"functions": 70,
"statements": 70
}
Specifically in the example above, a limit of 70% is stated for all the metrics, so if any of them fall bellow that value nyc
will trigger an error.
Have in mind that coverage checking is only applied to the metrics of all files, so if you have a project with two files, one of them with a statement coverage of 60% and the other with a statement coverage of 90%, since the average of all two files is 75% the coverage check will pass, even having a file with the metrics below the threshold.
Comentarios
Publicar un comentario