簡體   English   中英

開玩笑的單元測試和重試-axios node.js

[英]jest unit test and retry-axios node.js

我一直在嘗試使用 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);

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);
      }
    });

無論我嘗試過什么,關於“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}; });

謝謝你。 如果您需要更多詳細信息,請告訴我。

我知道這個問題很老,但我只花了 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()
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM