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();
});
});
});