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.