Created
March 5, 2021 20:14
-
-
Save tharun208/3a94457e3e8b6e7d09e21601f57a6443 to your computer and use it in GitHub Desktop.
Axios mocking using jest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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