0

I am trying to test my all api calls function by some method but all the time i am getting error, so what is the best way to test my all api calls library and other function, here so far what i did for testing.

Here is get my car functions for api

const api = `${api1}cars/Car
export async function getMyCar(value, to, from, year, month) {
  let products = new Promise((resolve, reject) => {
    fetch(
      `${api}?type=${value ? value : ""}&date__lte=${
        to ? to : ""
      }&date__gte=${from ? from : ""}&date__year=${
        year ? year : ""
      }&date__month=${month ? month : ""}`,
      config.head
    )
      .then((response) => {
        resolve(response.json());
      })
      .catch((reject) => console.log(reject));
  });
  return products;
}

Car.test.js

import mockAxios from "axios";
import { getMyCar } from "../../Service/Car";
import config from "../Main";

describe("Car Components component", () => {
  describe("when rendered", () => {
    it("should call a fetchData function", (done) => {
      getMyCar().then((response) => {
        expect(response).toEqual({
          data: [],
        });
      });
      expect(mockAxios.request).toHaveBeenCalledWith({
        method: "GET",
        url: config.car,
        Authorization: "Bearer c8NSnS84hIHiPP3PHZ8f5ZqKwv16lA",
      });
      expect(mockAxios.request).toHaveBeenCalledTimes(1);
      expect(consoleErrorSpy).not.toHaveBeenCalled();
      done();
    });
  });
});

Another method i tried like this.

import React from "react";
import { shallow } from "enzyme";
import MyDriver from "../MainDashboard/MyDriver/MyDriver";
import axios from "axios";
import Adapter from "enzyme-adapter-react-16";

import React from "react";
import { shallow } from "enzyme";
import MyDriver from "../MainDashboard/MyDriver/MyDriver";
import axios from "axios";
import Adapter from "enzyme-adapter-react-16";
jest.mock("axios");

describe("ToDoList component", () => {
  describe("when rendered", () => {
    it("should fetch a list of tasks", () => {
      const fetchSpy = jest.spyOn(axios, "get");
      const toDoListInstance = shallow(<MyDriver />);
      expect(fetchSpy).toBeCalled();
    });
});
});
skyboyer
  • 22,209
  • 7
  • 57
  • 64
rahul raj
  • 21
  • 1
  • 8
  • [Promise constructor anti-pattern.](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – Jared Smith Oct 05 '20 at 12:54

1 Answers1

0

Try this... It should work.

global.fetch = jest.fn();
const mockAPICall = (option, data) => global.fetch.mockImplementation(() => Promise[option](data));

describe("Car Components component", () => {
  describe("when rendered", () => {
    it("should call a fetchData function", async () => {
      const mockResponse = {
        data: []
      };
      mockAPICall("resolve", mockResponse);
      return getMyCar().then((response) => {
        expect(response).toEqual({
          data: []
        });
      });
    });
  });
});

You can use 'mockAPICall' for other API's too. Don't forget to clear your mocked 'fetch' incase you are using it in other test cases.

global.fetch.mockClear();
Paveloosha
  • 563
  • 2
  • 6
  • 15
  • i am getting `error : Timeout - Async callback was not invoked within the 30000ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 30000ms timeout specified by jest.setTimeout.Error:` @Paveloosha – rahul raj Oct 05 '20 at 13:17
  • @rahul, can you try 'async' before passing the test function and see. – Paveloosha Oct 05 '20 at 13:40
  • Hey, i tried `it("should call a fetchData function", async () => {` but still same error – rahul raj Oct 05 '20 at 13:49
  • @Rahul, we don't need 'getMyCar' as 'async' function. Please remove that and test. As well as from test case part. – Paveloosha Oct 05 '20 at 14:42