Why do the async functions appear to be uncovered branches in the Jest/Istanbul coverage report?

I am encountering an issue throughout my application: When running Jest test coverage script with Istanbul, I am getting a "branch not covered" message specifically on the async function part of my well covered function. What does this message mean and how can I address it?

I am not sure what exactly is uncovered in these functions.

For example, here is a test case for the "getPolicyStatsAPI" function: The remaining functions are tested in a similar manner. I don't think the solution lies within the test suites, but I can provide them if necessary.

  describe(`API Calls`, () => {
    const mockFetch = jest.fn()
    global.fetch = mockFetch
    beforeEach(() => {
      mockFetch.mockClear()
    })
    test('getPolicyStatsAPI fetches the data and returns it as expected', async () => {
      mockFetch.mockReturnValueOnce(createAPIResponse(policySearchState))

      const response = await getPolicyStatsAPI(reqBody)
      expect(fetch).toBeCalledTimes(1)
      expect(response).toEqual(policySearchState.data)
    })
    test('getPolicyStatsAPI returns error on exception', async () => {
      const error = new Error(errorMessage)
      // eslint-disable-next-line prefer-promise-reject-errors
      mockFetch.mockImplementationOnce(() => Promise.reject(errorMessage))
      await expect(getPolicyStatsAPI(reqBody)).rejects.toEqual(error)
      expect(fetch).toBeCalledTimes(1)
    })
  })

The section of code triggering the "branch not covered" warning is as follows: The warning highlight specifically appears over the "async function" part of the code, marked in yellow.

export async function getPolicyStatsAPI(reqBody: APIRequestBody) {
  const body: APIRequestBody = {
    ...reqBody,
  }
  type ExpectedResponse = { data: PolicyStats[] }
  const response = await callAPI<ExpectedResponse>({
    url: Endpoint.POLICY_STATS,
    method: 'POST',
    body,
  })
  return response.data
}

Test coverage report screenshot:

https://i.sstatic.net/Fs9kL.png

Answer №1

After posting my comment, I decided to experiment with some other solutions independently. Surprisingly, one of the fixes that worked for me was deleting the transform section in my jest.config.js:

module.exports = {
  ...
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.test.json',
      babelConfig: 'babel.config.js'
    },
  },

  // I removed this part:
  // transform: {
  //   '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
  //   '^.+\\.(ts|tsx)?$': 'ts-jest',
  // },

  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      'identity-obj-proxy',
  },
  ..
}

I can't guarantee it will work for your project, but it's worth a shot.

Answer №2

Each asynchronous function should include an await keyword:

    mockFetch.mockReturnValueOnce(await createAPIResponse(policySearchState))

    const response = await getPolicyStatsAPI(reqBody)

    expect(response).toEqual(await policySearchState.data)

    await expect(await getPolicyStatsAPI(reqBody)).rejects.toEqual(error)

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

Incorporate real-time calculations using JavaScript (jQuery) with variables including initialization in HTML code

As a newcomer to JavaScript, I am encountering an issue that I need help with: I would like to convert the value in the number box into the answer next to it without any changes to the value. This should also include the variables NP0, NP1, and DP0 from t ...

Difficulty encountered while implementing mouseover event listener for an SVG component

I'm having trouble triggering an event for an svg element. Here's the link to my jsfiddle example: https://jsfiddle.net/r1ahq5sa/ Here's the HTML code: <div class="row"> <div class="col-md-8"> <svg class="video-nav-bar ...

Encountering a 401 error message with a 'truncated server' response while using Google Apps Script

I'm currently working on a code snippet that looks like this. function method3() { var spreadsheetID = '1BGi80ZBoChrMXGOyCbu2pn0ptIL6uve2ib62gV-db_o'; var sheetName = 'Form Responses 1'; var queryColumnLetterStart = ...

SyntaxError: Unexpected symbol

I have an issue with the following code: let op = data.map(({usp-custom-90})=> usp-custom-90 ) When I run it, I encounter the following error: Uncaught SyntaxError: Unexpected token - I attempted to fix it by replacing the dash with –, but t ...

Arrangement of watch attachment and $timeout binding

I recently encountered a component code that sets the HTML content using $scope.htmlContent = $sce.trustAsHtml(content). Subsequently, it calls a function within a $timeout to search for an element inside that content using $element.find('.stuff' ...

Displaying fresh data from a JSON URL by clicking on a button and dynamically refreshing the view in

Apologies if this question has been asked before, but I couldn't locate it. I’m currently engaged in an Angular project where I’ve loaded an external JSON file using http. The data is presented through ngRepeat. When a button is clicked, I aim t ...

Exploring Date Comparisons in AngularJS

Currently, I am in the process of developing a web application using AngularJS and Rails. One of the features involves creating bookings through a bookings function. In the dashboard section of the app, I aim to have two tabs - one for Current Bookings and ...

What is a way to automatically run a function at specific intervals in PHP, similar to the setTimeout() function in JavaScript?

I have a JavaScript code snippet that looks like this: setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); Now, I want to execute the following PHP function every 1000 milliseconds, similar to the above JavaScript code: $notific ...

Submitting a form without refreshing the page, displaying the output, reloading the form, and repeating the process. Wash,

There is a form on my page with dynamic drop-down options, an input box, and a submit button. To include this form on my page, I use the following code: <div id="dropdown"> <?php include("./listforward.php"); ?> </div> The listfo ...

An unusual 'GET' request has been made to the '/json/version' endpoint in Express.js

Hey there, I'm facing a challenge with my Express project. For some reason, I keep receiving a 404 error due to a mysterious GET request to '/json/version'. The request seems to bypass the defined routers after adding session data and eventu ...

Modify the data in the <col> column

Is it feasible to update the values in a particular column of a table? <table> <col with="auto"> <col with="auto"> <col with="auto" id="update_me"> <?php for(hundreds of lines){ ?> <tr> <td>so ...

`How can I activate caching for getServerSideProps in Next.js?`

We have implemented server-side rendering for a few pages and components. In an attempt to optimize performance, we have been experimenting with caching API responses. export async function getServerSideProps(context) { const res = await getRequest(API ...

javascript - A single image within the array fails to load

I'm encountering a challenge while trying to preload images in an array for later use in drawing on a canvas, such as in a 2D top-down game board. Interestingly, one of these images (which are Greyscale GIFs, by the way) refuses to load. It's evi ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Utilizing AJAX to dynamically update a div's content by extracting a specific div from the retrieved data

Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat m ...

Guide on implementing a personalized 'editComponent' feature in material-table

I'm currently integrating 'material-table' into my project. In the 'icon' column, I have icon names that I want to be able to change by selecting them from an external dialog. However, I am encountering issues when trying to update ...

Encountering a TypeScript Issue When Implementing an Interface

Compiler Error- Issue with 'MessageBus' Class: Property 'dispatch' is missing in the implementation of interface 'IMessageBus'. IMessageBus Interface- export interface IMessageBus { dispatch: (eventName: string, info?: ...

Expanding a Node.js class to incorporate additional static class elements

I have a query where I believe that extending a class might be the solution, but I am not entirely sure. Here is the scenario... There is a class defined as follows: class Field { apiName; /** * Creates an instance of Field with the given par ...

JQuery selector is successfully working while vanilla JavaScript is not functioning as expected

This problem is unique because I am experiencing issues with querySelector and querySelectorAll in my JavaScript code. While JQuery works fine, vanilla JS does not work as expected. I would appreciate any insights on why this might be happening. Thank you ...

Is it possible to find out which JavaScript file the AJAX function is using to send a request to a Java servlet?

I am facing an issue with two js files, one.js and two.js. Both of these files make ajax requests to the same Java servlet class(AppController.java). Here is the code from one.js: function addOne(){ var formData = $('#form1').serialize(); ...