7.1 Setting Coverage Thresholds
Coverage thresholds allow you to define a percentage under which you jest --coverage
run will start failing.
To add coverage to a project, we should start by seeing what coverage we get from jest --coverage
.
Now there are 4 types of coverage reported. These are also the specific thresholds we can set.
Stmts
is statement coverage ie. the number of statements that are run during the test run vs how many are in a given files.
Branch
is branch coverage ie. the number of branches (if/else, ternary, switch cases) that are run during the test run vs how many are in a given file.
Funcs
is function coverage ie. the number of functions that are run during the test run vs how many are in a given file.
Lines
is line coverage ie. the number of lines that are run during the test run vs how many are in a given lines.
For each of these coverage measurements we can set a threshold in our jest config. In this case, we’ll use the jest
key in package.json
and update it as follows.
The following coverageThreshold
configuration set the minimum branch coverage at 10%, function coverage at 80%, line coverage at 80% and statement coverage at 80%.
{
"//": "// other properties",
"jest": {
"//": "// other properties",
"coverageThreshold": {
"global": {
"branches": 10,
"functions": 80,
"lines": 80,
"statements": 80
}
}
}
}
When runnning npm test -- --coverage
we get the following failure.
If we drop the functions coverage to 78
, as per the following configuration object.
{
"//": "// other properties",
"jest": {
"//": "// other properties",
"coverageThreshold": {
"global": {
"branches": 10,
"functions": 78,
"lines": 80,
"statements": 80
}
}
}
}
We’ll get npm t -- --coverage passing