Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the uncovered parts of code in jest

I wrote a simple reducer :

const simpleCounterReducer = (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT_COUNT':
            return state + 1;
        case 'DECREMENT_COUNT':
            return state - 1;
        default:
            return state;
    }
};

export default simpleCounterReducer;

And then a few simple tests to cover all the possible options.

import simpleCounterReducer from '../src/reducers/simple-counter.js';

describe('counter works and', () => {
    test('can handle increments', () => {
        expect(
            simpleCounterReducer(0, {
                type: 'INCREMENT_COUNT'
            })
        ).toBe(1);
    });

    test('can handle decrements', () => {
        expect(
            simpleCounterReducer(1, {
                type: 'DECREMENT_COUNT'
            })
        ).toBe(0);
    });

    test('can handle invalid actions', () => {
        expect(
            simpleCounterReducer(4, {
                type: 'SOME_RANDOM_ACTION'
            })
        ).toBe(4);
    });
});

Then I ran this command : npx jest --colors --coverage

But even though I have covered all parts of the code, I am getting an uncovered line. Is it something wrong with jest or am I missing something. And is there a way to find out in jest, the parts of code that are not covered.

Image for jest test coverage output

like image 521
Aman Kumar Avatar asked Feb 01 '19 19:02

Aman Kumar


People also ask

What is uncovered line in Jest?

The uncovered lines marked in yellow are part of code branches (if-else statements, ternary operators or else). Corrsponding to that you can see that our branch coverage is at 75% and therefore not complete yet.

Does Jest have code coverage?

Jest, a flexible, easy-to-use testing framework, will be used to test a simple Typescript application. Codecov, a tool for monitoring code coverage, will be used to measure the test coverage for your Jest unit tests.

What does coverage do in Jest?

Code coverage makes possible to spot untested paths in our code. It is an important metric for determining the health of a project. I've seen enough misconfigured JavaScript projects where Jest coverage were reported incorrectly.


1 Answers

If you want to see the lines that are not covered you can open in a browser the generated report.

By default the report is here ./coverage/lcov-report/index.html.

But you also see in the console the line numbers of the uncovered lines (it is not the number of lines that are not cover but the line numbers, and in your case it is the first line).

Also some config for the coverage if needed : https://jestjs.io/docs/en/configuration#collectcoverage-boolean

Side note, it uses istanbul behind the scene : https://github.com/gotwarlost/istanbul

like image 169
BenoitVasseur Avatar answered Oct 01 '22 22:10

BenoitVasseur