Home > Mobile >  React jest tests not hitting coverage for api
React jest tests not hitting coverage for api

Time:03-10

I have this api code called in some components.

const Api: IApi = {
  delete: (url: string): Promise<any> => {
    return axios.delete(url);
  },
  get: (url: string): Promise<any>  => {
    return axios.get(url)
  },
  post: (url: string, payload: IContact): Promise<any> => {
    return axios.post(url, JSON.stringify(payload))
  },
  put: (url: string, payload: IContact): Promise<any>  => {
    return axios.put(url, JSON.stringify(payload))
  },
}

export { Api }

All the components that use this api have been tested to 100% coverage except the API. enter image description here

The files without coverage are interface (types) files.

The issue I am facing now is to try and test the API so it hits 100% coverage but all scenarios have failed. The get method only is covered even though all the other methods have been successfully mocked.

What is really going on here for the coverage to behave like this?

enter image description here

How can this coverage be achieved?

CodePudding user response:

You should mock the axios library, call the delete, post & put methods in your tests and make sure the mocks are correctly called.

Something like this:

import axios from 'axios';
import { Api } from './users';

jest.mock('axios');

describe('Api', => {
  it('should call delete correctly', () => {
    const url = 'https://stackoverflow.com/';

    Api.delete(url);

    expect(axios.delete).toHaveBeenCalledWith(url);
  });
});
  • Related