use*_*573 6 typescript jestjs retry-axios
我一直在尝试使用 retry-axios 库并断言“get”被调用的次数,但没有任何运气。这是我的设置:
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);
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
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);
}
});
Run Code Online (Sandbox Code Playgroud)
无论我尝试过什么,有关“get”调用数量的断言始终为 1。
以下是我在第一次尝试时尝试在模拟拒绝时抛出错误的其他一些事情:
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}; });
Run Code Online (Sandbox Code Playgroud)
谢谢。如果您需要更多详细信息,请告诉我。
我知道这个问题很老了,但我只花了 3 个小时来尝试解决同样的问题。解决方案将使用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()
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2864 次 |
| 最近记录: |