javascript - 如何使用 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);
});
});
}
对上述重试功能进行如下测试。
- 总是传递一个promise来resolve,并且retry函数在第一次执行时被resolve
- 在第三次运行时通过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 递归处理。
解决方案
也许您的 retry
任务需要太多次(例如:)4,9s
,然后您没有足够的时间来做下一个测试用例。
你可以增加timeout
JEST 的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);
});
推荐阅读
- php - 在laravel上设置Excel列号格式为文本
- python - 如何使用python计算信噪比
- stata - 在 foreach 循环中,如何找到相应变量左侧两列的平均值?
- javascript - Math.sin() 方法保持返回值 1,而不是 -1~1
- python-3.x - Python:减去 HDF5 文件数据集元素的最快方法?
- javascript - 将变量传递给 express.js 中 req 中的下一个中间件
- java - 如何从地图中获取前 M 值?
- r - 简单的网页抓取问题 - rvest
- ios - 在 Swift 中使用 PropertyListDecoder 时从 plist 解析浮点值时出现解码错误
- shopware - Shopware6:缺少插件配置