I've been attempting to utilize the retry-axios library and verify the number of "get" calls made without success. Here's how I've set it up:
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 successfully call the end point if 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);
}
});
No matter what I try, the assertion regarding the number of "get" calls always returns 1.
Below are some other attempts I made by throwing an error when 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 require any further details.