Skip to content

Instantly share code, notes, and snippets.

@tharun208
Created March 5, 2021 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tharun208/3a94457e3e8b6e7d09e21601f57a6443 to your computer and use it in GitHub Desktop.
Save tharun208/3a94457e3e8b6e7d09e21601f57a6443 to your computer and use it in GitHub Desktop.
Axios mocking using jest
const axios = require("axios");
const { fetchData } = require("./server");
jest.mock("axios");
const mockServerErrorResponse = {
response: {
status: 500,
data: "system error",
},
};
const mockResponse = {
data: [
{
month: "2014-07-01T00:00:00.000",
},
],
};
describe("client test", () => {
const date = "2014-07-01";
it("should able to make a call to api with given params", async () => {
try {
await fetchData(date);
} catch (e) {
// fail("exception occured", e)
}
expect(axios).toHaveBeenCalledTimes(1);
expect(axios).toHaveBeenCalledWith({
method: "get",
url: "https://data.lacity.org/resource/trxm-jn3c.json?month=2014-07-01",
});
});
it.only("should return empty array if api returns error", async () => {
axios.mockReturnValue(Promise.reject(mockServerErrorResponse));
const errorResponse = await fetchData(date);
expect(axios).toHaveBeenCalledTimes(1);
expect(errorResponse).toEqual([]);
});
it("should able to return success response", async () => {
axios.mockReturnValue(Promise.resolve(mockResponse));
const response = await fetchData(date);
expect(axios).toHaveBeenCalledTimes(1);
expect(response).toEqual([{ month: "2014-07-01T00:00:00.000" }]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment