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.
A retry with a 1 second backoff should not make the suite wait 3 seconds. Fake the timers and count the attempts.
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();
}); ✓ 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.