Skip to content

Commit

Permalink
test(utils): case for delay
Browse files Browse the repository at this point in the history
  • Loading branch information
homura committed Nov 29, 2023
1 parent 03303f6 commit 0b8d3c0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
6 changes: 3 additions & 3 deletions packages/utils/src/async/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,13 @@ export function retry<T>(

const retryPromise = new Promise<T>((resolve, reject) => {
function handleError(err: unknown) {
currentRetryTimes++;

if (currentRetryTimes >= retries) {
if (currentRetryTimes > retries) {
reject(err);
return;
}

currentRetryTimes++;

if (delayMs) {
delay(delayMs).then(retryRun);
} else {
Expand Down
27 changes: 23 additions & 4 deletions packages/utils/tests/async.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@ test("async#timeout", async (t) => {

test("async#retry", async (t) => {
function passOn(times: number): () => Promise<void> {
let count = 0;
let runTimes = 0;
return () =>
new Promise<void>((resolve, reject) => {
count++;
if (count >= times) resolve();
else reject(new Error("Failed"));
if (runTimes > times) {
return resolve();
}
runTimes++;
reject(new Error("Failed"));
});
}

Expand Down Expand Up @@ -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);
});

0 comments on commit 0b8d3c0

Please sign in to comment.