简体   繁体   中英

How to test promise recursion with JEST

I write a test using JEST. I do not know how to test promise recursion in JEST.

In this test, the retry function that performs recursion is the target of the test until the promise is resolved.

export function retry <T> (fn: () => Promise <T>, limit: number = 5, interval: number = 10): Promise <T> {
  return new Promise ((resolve, reject) => {
    fn ()
      .then (resolve)
      .catch ((error) => {
        setTimeout (async () => {
          // Reject if the upper limit number of retries is exceeded
          if (limit === 1) {
            reject (error);
            return;
          }
          // If it is less than the upper limit number of retries, execute callback processing recursively
          await retry (fn, limit-1, interval);
        }, interval);
      });
  });
}

Perform the following test on the above retry function.

  1. Always pass a promise to resolve, and the retry function is resolved on the first execution
  2. Pass the resolve to resolve on the third run, and the retry function is resolved on the third run

I thought it would be as follows when writing these in JEST.

describe ('retry', () => {
  test ('resolve on the first call', async () => {
    const fn = jest.fn (). mockResolvedValue ('resolve!');
    await retry (fn);
    expect (fn.mock.calls.length) .toBe (1);
  });

  test ('resolve on the third call', async () => {
    const fn = jest.fn ()
               .mockRejectedValueOnce (new Error ('Async error'))
               .mockRejectedValueOnce (new Error ('Async error'))
               .mockResolvedValue ('OK');
    expect (fn.mock.calls.length) .toBe (3)
  });
});

As a result, it failed in the following error.

Timeout-Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:
    > 40 | test ('resolve on the third call', async () => {
         | ^
      41 | const fn = jest
      42 | .fn ()
      43 | .mockRejectedValueOnce (new Error ('Async error'))

I think that it will be manageable in the setting of JEST regarding this error. However, fundamentally, I do not know how to test promise recursive processing in JEST.

Maybe your retry task take too many times (ex: 4,9s ), then you do not have enough time to do next test case.

You can increase the timeout of JEST with jest.setTimeout(10000);

Promise testing official document.

My solution for your case:

test("resolve on the third call", async () => {
    jest.setTimeout(10000);
    const fn = jest.fn()
      .mockRejectedValueOnce(new Error("Async error"))
      .mockRejectedValueOnce(new Error("Async error"))
      .mockResolvedValue("OK");

    // test reject value
    await expect(fn()).rejects.toEqual(new Error("Async error"));
    await expect(fn()).rejects.toEqual(new Error("Async error"));

    // test resolve
    const result = await fn();
    expect(result).toEqual("OK");

    // call time
    expect(fn).toHaveBeenCalledTimes(3);
  });

The timeout happens because .catch() handler in retry() does not call resolve when it does second attempt to call retry() ; so the first retry() returns a promise which is never resolved or rejected.

Replacing await with resolve() might help (and function in setTimeout need not to be async then):

  .catch ((error) => {
    setTimeout (() => {
      // Reject if the upper limit number of retries is exceeded
      if (limit === 1) {
        reject (error);
        return;
      }
      // If it is less than the upper limit number of retries, execute callback processing recursively
      resolve(retry (fn, limit-1, interval));
    }, interval);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM