最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test promise recursion with JEST - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited May 14, 2019 at 11:24 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked May 14, 2019 at 0:01 wato9902wato9902 65910 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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);
发布评论

评论列表(0)

  1. 暂无评论