Skip to content
jshacks.dev
Testing

Test an async function that retries

Test a retry helper by failing a mock twice then succeeding, and advance fake timers so the backoff delays do not slow the Vitest run.

1 min read
Summarize in AI

A retry with a 1 second backoff should not make the suite wait 3 seconds. Fake the timers and count the attempts.

retry.test.jsJavaScript
import { test, expect, vi } from 'vitest';

async function retry(fn, attempts, delayMs) {
  for (let i = 1; ; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i >= attempts) throw error;
      await new Promise((resolve) => setTimeout(resolve, delayMs));
    }
  }
}

test('succeeds on the third attempt', async () => {
  vi.useFakeTimers();
  const fn = vi.fn()
    .mockRejectedValueOnce(new Error('one'))
    .mockRejectedValueOnce(new Error('two'))
    .mockResolvedValue('ok');

  const promise = retry(fn, 3, 1000);
  await vi.advanceTimersByTimeAsync(2000);

  await expect(promise).resolves.toBe('ok');
  expect(fn).toHaveBeenCalledTimes(3);
  vi.useRealTimers();
});
Text
 ✓ retry.test.js (1 test)

 Test Files  1 passed (1)
      Tests  1 passed (1)

mockRejectedValueOnce queues one failure per call, then mockResolvedValue takes over. The async timer helper runs each pending timer and flushes promises in between. See mockRejectedValueOnce.

Also test the exhausted case, where every attempt fails and the last error is thrown.

Also test the case where every attempt fails and assert the final error is the one thrown, because that path is where a retry helper most often leaks the wrong error. A third check worth adding is the number of calls made, which proves the loop stops at the limit and never retries forever.

Also inAsync
Taggedvitest
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.