How to export a delay for unit testing

35 Views Asked by At

I am attempting to test if an API retry is happening with the appropriate amount delay. In my client, I have the following code.

      if (isExpBackOffStatusError) {
        // retry with exp backoff delay
        const retries = this.retryConfig.retryAttempts - retriesRemaining;
        const randomNumberMilliseconds = Math.floor(Math.random() * 101) - 50;
        const maximumBackoff =
          this.retryConfig.retryDelay *
          3 ** (this.retryConfig.retryAttempts - 1);

        const del = Math.min(
          this.retryConfig.retryDelay * 3 ** retries + randomNumberMilliseconds,
          maximumBackoff
        );

        //want to test how long this delay is
        await delay(del);

At the end of this file I export delay by doing the following export const delay = promisify(setTimeout);

Below is my unit test file. The tests uses Mocha and Sinon Mocks.

  it('post() performs two retries with exponential backoff delay with an unsuccessful status 429 and base delay of 0.25 seconds', async () => {
    const axiosPost = {
      post: sandbox.stub().resolves({ status: 429 }),
    };
    const apiClient = new ApiClient(
      axiosPost as unknown as AxiosInstance,
      '',
      oauthStub as unknown as OAuther,
      { retryAttempts: 2, retryDelay: 250 }
    );

    await apiClient.post('', {}, {}, 'clientCorrelationID');
   
    assert.calledThrice(axiosPost.post);
    //need to add a test that will test how long each delay was 
  });

this unit test ensures that the api call was made three times (one original call + two retries). Afterwards, I want to check that each call had the correct millisecond delay (i.e., 0.25s between original call and first retry and 0.75s between first retry and second retry.)

My idea was to somehow export that value for the delay and check its value in the unit test. However, I am 1. unsure if I am exporting this correctly, 2. unsure if this is the best way to test the delay.

0

There are 0 best solutions below