What could be the reason for Jest coverage reporting 0 branches covered in this Vue component method with Istanbul?

Take a look at this 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 have written a unit test for this component using Jest:

// 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 successfully.

However, when running Jest with --coverage, the summary report shows low coverage:

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

It seems that no branches are covered, even though two lines of code are detected as covered.

After adding an if statement inside onClick(), one branch was counted as covered by Jest:

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

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

Answer №1

It appears that there may be a misunderstanding regarding the concept of branches in programming.

A statement within code is akin to a single line of instruction. A branch, on the other hand, arises when certain conditions determine whether specific statements will be executed or not.

In the code snippet below, no branches are present:

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

This lack of branches is due to the absence of any conditional statements such as an if.

However, in the subsequent code snippet, two branches are evident: one for the if condition and another for the implied else scenario.

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

To ensure all branches are addressed, it would be necessary to include a test for when this.text is undefined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected event in Coffeescript and Express framework: a tangled web of mysteries

Currently, I am working on developing an app using Express.js and Coffeescript. My code can be found here: https://github.com/findjashua/contactlist However, upon trying to run the application, I encounter the following error: app.coffee:11:24: error: un ...

Access an object's property from within a callback function

I have an async.series() function that is calling a method from another Javascript object: main.js var obj1 = require('./obj1'); var obj2 = require('./obj2'); async.series([ obj1.myFunc1, obj2.anotherFunc ]); obj1.js module ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Securing routes with passport.js in a MEAN Stack setting

I am facing an issue with securing individual routes in my admin panel using passport.js. The user signup functionality is working fine, and I am able to login successfully. However, the req.isAuthenticated() function always returns false, preventing me fr ...

Retrieve a collection of JSON files using a single function

The format of JSON links is as follows: www.example.com/link-number-end-of-link.com.json I need to retrieve multiple JSON link files where the only variable changing is the number in the link. For example, it could range from 10 to 40, with the first ...

What is causing the sorting table to fail in React when using useState?

import React, { useState } from "react"; import "./App.css"; const App = () => { const [data, setData] = useState([ { rank: 1, name: "John", age: 29, job: "Web developer", }, { rank: 2, name: "Micha ...

How can I remove ASCII characters from an ajax response?

Experimenting with the API found at , but encountered an issue with properly formatting the received string. The string looks like this: Communication that doesn&#8217;t take a chance doesn&#8217;t stand a chance. The original response includes a ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...

What is the best approach for sending a binary image post request to an API using nodejs?

I am receiving the image binary in this manner: axios.get("image-url.jpg") Now, I want to utilize the response to create a new POST request to another server const form = new FormData(); const url = "post-url-here.com"; form.appe ...

Exploring the single slot functionality in components: A step-by-step guide

`I'm working on a component with multiple slots, namely: header slot, main slot, and footer slot base-layout.vue <template> <div class="container"> <header> <slot name="header"></slot> ...

What factors determine when Angular automatically triggers a setTimeout function compared to another?

Sorry if this all seems a bit odd, but I'll do my best to explain the situation. We have been given access to a small service that provides a simple form UI which we collect results from using an event. We've successfully implemented this in two ...

Error: An unexpected TypeError occurred while attempting to fetch an array or collection from MongoDB Atlas

As a beginner in the world of Express and Mongoose, I am currently working on retrieving an object from MongoDB Atlas using Mongoose.Model for educational purposes. In CoursesModel.js, I have defined the schema for my collections and attempted to fetch it ...

Have you ever encountered the frustration of being unable to navigate to the next page even after successfully logging in due to issues

I'm currently utilizing Vue and Firebase to build my application. One of the features I want to implement is the redirect method using vue-router. Within my vue-router code, I've included meta: { requiresAuth: true } in multiple pages as middlew ...

Exploring discrepancies in JSON arrays using Lodash

Using lodash to find the difference between two arrays: c1Arr contains: [ { varName: 'city', varValue: 'cccccccc' }, { varName: 'country', varValue: 'dddddddd' } ] c2Arr contains: [ { varName: 'abc', ...

Encountering error #426 in NextJs when the app is loaded for the first time in a new browser, but only in a

Encountering a strange error exclusively in production, particularly when loading the site for the first time on a new browser or after clearing all caches. The website is built using nextjs 13.2.3 and hosted on Vercel. Refer to the screenshot below: http ...

Transform this JavaScript into Vue 3 code

Hey there! I'm currently working on implementing dark mode into my project by following a tutorial. However, the tutorial is based on JavaScript and not Vue, so I'm having some trouble converting this particular section of code to work with Vue 3 ...

What is the best way to give stacked bar charts a rounded top and bottom edge?

Looking for recommendations on integrating c3.js chart library into an Angular 6 project. Any advice or suggestions would be greatly appreciated! https://i.sstatic.net/iiT9e.png ...

Is it possible to change the text of a scrollspy dropdown to a default text when it is not actively tracking any items?

I am new to Vue and currently implementing Bootstrap Vue Scrollspy (view example here). My sticky dropdown is tracking all referenced content and updates with the current section in view. You can check out my code sample here. Is there a way to set the d ...

Problem with parsing JSON in a mixed array

When making a YouTube API call, the response includes a var result = JSON.stringify(response, '', 2); that has the following structure: { "kind": "youtube#searchListResponse", "pageInfo": { "totalResults": 1000000, ...

Failed to complete the Vue.js project build process in the Gitlab CI/CD pipeline

During the deployment of my project using Gitlab CI/CD, I encountered an issue with dependencies. Everything functions correctly locally, but not within the pipeline. .gitlab-ci.yml: stages: - build-frontend - build-backend image: lnkra/<...project n ...