Jest: Code Coverage

Ifeoluwa Akinremi Wade
3 min readMar 6, 2022
Sam Smith (Code Coverage in GitHub with .NET Core)

What is “code coverage”?

Code coverage is a metric that can help you understand how much of your source is tested. It’s a very useful metric that can help you assess the quality of your test suite (Sten Pittet, An introduction to code coverage)

Why?

Code coverage allows for the detecting of untested code in your application.

Getting Started

If you are at this point of your learning about Jest TDD, then you are already familiar with Jest basics.
To implement code coverage, please head over to your package.json file of your application and do the following:
You will add the flag --collectCoverage in the test script. So,

"scripts": {
"test": "jest --collectCoverage"
},

Your package.json should look similar to this:

In The Thick Of It

Remember that the benefit of code coverage is to keep track of the code that is being tested. This is definitely useful for big applications.

Reading Code Coverage In the Terminal

Ebenezer Don (intro to Test Driven Development (TDD) with Jest — a Very Simple Guide)

The images above is what will appear in your terminal after you run your tests with code coverage. But what the hell does this all mean?

Let’s break it down.

File
As you can see all the files containing the code source being tested are listed and accounted for. These files are the files that will have their code coverage measured.

Statements (% Stmts)
The percentage of statements within the code being executed at least once. ie: A variable declaration is a statement, const foo = 'foo' . Here is documentation about Javascript statements.

Branch (% Branch)
Branches are where code can take different paths, or routes. A great example of branch statements is if/else statements. Here is where I found great explanations of Branch, as it does get confusing to conceptualize.

Functions (% Funcs)
The percentage of functions that are called at least once.

Lines (% Lines)
The percentage of lines of code that executed at least once. Not to be confused with statements. This is measuring whether each executable line in the code has been covered. ie: let x = 20; console.log(x) is one line of two statements.

Uncovered Line #s
Here will display the lines of code that are present within your code, but were not tested.

--

--