From 0b8d3c09199faf9f23ed7106a90cb721f3967888 Mon Sep 17 00:00:00 2001 From: homura Date: Wed, 29 Nov 2023 15:47:53 +0800 Subject: [PATCH] test(utils): case for delay --- packages/utils/src/async/index.ts | 6 +++--- packages/utils/tests/async.test.ts | 27 +++++++++++++++++++++++---- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/packages/utils/src/async/index.ts b/packages/utils/src/async/index.ts index ec08ecfd9..493f25b5e 100644 --- a/packages/utils/src/async/index.ts +++ b/packages/utils/src/async/index.ts @@ -86,13 +86,13 @@ export function retry( const retryPromise = new Promise((resolve, reject) => { function handleError(err: unknown) { - currentRetryTimes++; - - if (currentRetryTimes >= retries) { + if (currentRetryTimes > retries) { reject(err); return; } + currentRetryTimes++; + if (delayMs) { delay(delayMs).then(retryRun); } else { diff --git a/packages/utils/tests/async.test.ts b/packages/utils/tests/async.test.ts index bf400f632..6e263a373 100644 --- a/packages/utils/tests/async.test.ts +++ b/packages/utils/tests/async.test.ts @@ -32,12 +32,14 @@ test("async#timeout", async (t) => { test("async#retry", async (t) => { function passOn(times: number): () => Promise { - let count = 0; + let runTimes = 0; return () => new Promise((resolve, reject) => { - count++; - if (count >= times) resolve(); - else reject(new Error("Failed")); + if (runTimes > times) { + return resolve(); + } + runTimes++; + reject(new Error("Failed")); }); } @@ -71,3 +73,20 @@ test("async#retry with timeout", async (t) => { t.true(called); t.true(failed); }); + +test("async#retry with delay", async (t) => { + const before = Date.now(); + + await t.throwsAsync(() => + retry( + () => { + throw new Error("delay"); + }, + { retries: 5, delay: 50, timeout: 1000 } + ) + ); + + const after = Date.now(); + + t.true(after - before >= 50 * 5); +});