Istanbul is the tool Jest uses to calculate test coverage. Sometimes we need to exclude some code from the coverage calculations. This is done with special comments which are parsed by Istanbul. There are a few variations of the syntax.
Ignore a Function
/* istanbul ignore next */ const f = () => { return 'abc' }
This will exclude the entire function from code coverage requirements.
Ignore a Whole File
/* istanbul ignore file */ ... file contents ...
Use this as the first line of the file. The entire file will be excluded from code coverage.
Ignore a Method in a Class
class A { f() { console.log("f called") } /* istanbul ignore next */ g() { console.log("g called") } }
The comment must be on or above the line defining the method so it is not part of the coverage requirement.
Function Inside an Exported Object
Sometimes we have a module which exports some functions inside an object.
The example below shows how to ignore these for coverage. The comment must be right before the function definition.
module.exports = { f: () => { console.log('f called') }, g: /* istanbul ignore next */ () => { console.log('g called') }, h: /* istanbul ignore next */ async () => { console.log('h called') } }
Note that for async functions we must place the comment before the async keyword.
Ignore Else Cases
To ignore just the else case of a block of code for test coverage, use the syntax as below.
function f(x) { /* istanbul ignore else */ if (x >= 0) { console.log('positive') } else { // Ignore this block for code coverage. console.log('negative') } }
NOTE: the ignore-else comment is placed above the if statement to ignore the else case for coverage.
References
https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md