Home » vue » Why does Jest coverage (Istanbul) measure 0 branches in this Vue component method?

Why does Jest coverage (Istanbul) measure 0 branches in this Vue component method?

Posted by: admin November 26, 2021 Leave a comment

Questions:

Please consider the following – somewhat contrived – Vue component:

<!-- FooBar.vue -->
<template>
    <div @click="onClick">{{text}}</div>
</template>

<script>
    export default {
        name: 'foo-bar',
        data() {
            return {
                text: 'foo'
            }
        },
        methods: {
            onClick() {
                this.text = 'bar';
            }
        }
    }
</script>

I’ve covered the component with a Jest unit test like so:

// FooBar.spec.js

import FooBar from '~/FooBar.vue';
import { shallowMount } from '@vue/test-utils';
import { expect } from 'chai';

describe('FooBar onClick()', () => {
    it('should change the text to "bar"', () => {
        // Arrange
        const target = shallowMount(FooBar);

        // Act
        target.trigger('click');

        // Assert
        const div = target.find('div');
        expect(div.text()).to.equal('bar');
    });
});

The test passes green.

When I run Jest with --coverage for this file, I get the following summary report:

=============================== Coverage summary ===============================
Statements   : 0.1% ( 2/1868 )
Branches     : 0% ( 0/1402 )
Functions    : 0% ( 0/505 )
Lines        : 0.2% ( 2/982 )
================================================================================

As you can see, the number of branches covered by the unit test is shown to be 0 – Even though Jest (or more accurately Instanbul, which Jest uses behind the scenes for coverage) did detect that the test covered two lines of code.

When I’ve made a tiny experiment and added an if statement inside onClick() like so:

onClick() {
    if (this.text != undefined) {
        this.text = 'bar';
    }
}

then Jest did indeed count 1 branch covered.

My question is – Why does Jest / Istanbul not count the code in the onClick() as a branch covered?

Answers:

I guess you misunderstand what a branch is.

A statement is similar to a line of code. A branch can only exist when a condition make some statements to be executed or not.

In the following code, there is no branch:

onClick() {
    this.text = 'bar';
}

This is because there is no if or any other sort of conditional statement.

In the following code, there are 2 branches: one for the if and one for the implicit else.

onClick() {
    if (this.text != undefined) {
        this.text = 'bar';
    }
}

If you wish to cover all branches, you need to add a test when this.text is undefined.