'jest unit test and retry-axios node.js
I have been trying to use the retry-axios library and assert the number of times in a "get" has been called without any luck. Here is my setup:
axios.config.ts
import axios, { AxiosInstance } from 'axios';
import * as rax from 'retry-axios';
export const axiosClient: AxiosInstance = axios.create({
raxConfig: {
retry: 3,
onRetryAttempt: (err: any) => {
const cfg = rax.getConfig(err);
console.error(`Retry attempt #${cfg?.currentRetryAttempt}`);
}
},
});
rax.attach(axiosClient);
api.service.ts
import { axiosClient } from 'axios.config';
export class ApiService
{
callApi = async (endPoint): Promise<any> => {
const response: AxiosResponse<any> = await axiosClient.get(endPoint);
return response.data;
};
api.service.spec.ts
import { ApiService } from 'api.service';
it('SHOULD call the end point successfully GIVEN THAT the first attempt fails and the second attempt succeeds.', async () => {
const service = new ApiService();
const apiResponse = { data: { content: [] } };
jest.spyOn(axiosClient, 'get').mockRejectedValueOnce(() => { throw 500 });
jest.spyOn(axiosClient, 'get').mockResolvedValueOnce(apiResponse);
try {
await service.callApi("endpoint");
}
catch (e) {
expect(axiosClient.get).toHaveBeenCalledTimes(2);
}
});
Whatever I have tried, the assertions about the number of "get" calls is always 1.
Here are a few other things I tried throwing an error on mocking the rejection on the first attempt:
jest.spyOn(axiosClient, 'get').mockImplementationOnce(async () => { throw 500; });
jest.spyOn(axiosClient, 'get').mockImplementationOnce(async () => { throw new Error(500) ;});
jest.spyOn(axiosClient, 'get').mockRejectedValueOnce(async () => { throw new Error(500); });
jest.spyOn(axiosClient, 'get').mockRejectedValueOnce(() => { return {statusCode: 500}; });
Thank you. Please let me know if you need anymore details.
Solution 1:[1]
I know that the question is old, but I just spent 3 hours on trying to solve the same problem. The solution would be using import MockAdapter from "axios-mock-adapter"
:
it("Should retry", async () => {
const mock = new MockAdapter(axios)
mock.onGet().replyOnce(500, {})
mock.onGet().replyOnce(200, validResponse)
callTheApiAndCheckResponse()
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Maria |