首页 > 解决方案 > 如何使用 JEST 测试 Promise 递归

问题描述

我使用 JEST 编写了一个测试。我不知道如何在 JEST 中测试 promise 递归。

在这个测试中,执行递归的重试函数是测试的目标,直到 promise 被解决。

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

对上述重试功能进行如下测试。

  1. 总是传递一个promise来resolve,并且retry函数在第一次执行时被resolve
  2. 在第三次运行时通过resolve来resolve,在第三次运行时retry函数被resolve

我认为在 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)
  });
});

结果,它在以下错误中失败。

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'))

我认为在 JEST 的设置中关于这个错误是可以管理的。但是,从根本上说,我不知道如何在 JEST 中测试 promise 递归处理。

标签: javascripttypescriptjestjs

解决方案


也许您的 retry任务需要太多次(例如:)4,9s,然后您没有足够的时间来做下一个测试用例。

你可以增加timeoutJEST 的jest.setTimeout(10000);

Promise 测试官方文档。

我对您的情况的解决方案:

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

推荐阅读