Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTesting

Test debounce and retries with fake timers

Use Vitest fake timers to assert debounce and promise-based retry behaviour without waiting on the real clock.

You wrote a debounced search handler and a test that waits 300 ms for the call to happen. Then you added a retry with backoff, and the suite waits another 300 ms before it can say anything. The tests pass, they are slow, and a busy CI machine makes them flaky.

Fake timers remove the wait. vi.useFakeTimers() replaces the timer functions with a clock your test controls, and vi.advanceTimersByTime(ms) moves that clock forward. No real time passes.

Debounce

The helper clears the pending timer on every call and starts a new one. The test calls it three times, then moves the clock.

// debounce.js
export function debounce(fn, wait) {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => fn(...args), wait)
  }
}

// debounce.test.js
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { debounce } from './debounce.js'

beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())

test('calls once, with the last arguments, after the wait', () => {
  const fn = vi.fn()
  const search = debounce(fn, 300)

  search('a')
  search('ab')
  search('abc')
  vi.advanceTimersByTime(299)
  expect(fn).not.toHaveBeenCalled()

  vi.advanceTimersByTime(1)
  expect(fn).toHaveBeenCalledTimes(1)
  expect(fn).toHaveBeenCalledWith('abc')
})

At 299 ms nothing has fired, and at 300 ms the spy has one call with 'abc'. The test takes a few milliseconds.

Switch back to real timers in afterEach. Otherwise the fake clock stays installed for the next test.

Retry with backoff

A retry helper awaits a promise and only then schedules its timer. When the first attempt rejects, the setTimeout does not exist yet at the moment the test calls vi.runAllTimers().

I ran that version. The test hung until Vitest gave up with Test timed out in 5000ms, its default limit.

The async variant, vi.runAllTimersAsync(), lets pending promise callbacks run between timers, so the timer created after the rejection exists by the time it looks.

// retry.js
export async function retry(task, { retries = 3, delay = 100 } = {}) {
  for (let attempt = 0; ; attempt++) {
    try {
      return await task()
    } catch (error) {
      if (attempt >= retries) throw error
      await new Promise((resolve) => setTimeout(resolve, delay * 2 ** attempt))
    }
  }
}

// retry.test.js
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { retry } from './retry.js'

beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())

test('retries with growing delays, then resolves', async () => {
  const task = vi
    .fn()
    .mockRejectedValueOnce(new Error('first'))
    .mockRejectedValueOnce(new Error('second'))
    .mockResolvedValue('ok')

  const result = retry(task, { retries: 3, delay: 100 })
  expect(task).toHaveBeenCalledTimes(1)
  await vi.advanceTimersByTimeAsync(99)
  expect(task).toHaveBeenCalledTimes(1)
  await vi.advanceTimersByTimeAsync(1)
  expect(task).toHaveBeenCalledTimes(2)
  await vi.advanceTimersByTimeAsync(199)
  expect(task).toHaveBeenCalledTimes(2)
  await vi.advanceTimersByTimeAsync(1)

  await expect(result).resolves.toBe('ok')
  expect(task).toHaveBeenCalledTimes(3)
})

The async clock advances let the promise handlers schedule each retry. Checking before and at 100 ms and 300 ms verifies both backoff intervals.

For the case where every attempt fails, attach the assertion before you run the timers: const assertion = expect(result).rejects.toThrow('down'), then await vi.runAllTimersAsync(), then await assertion. The rejection then has a handler when it happens.

Run it

pnpm exec vitest run --reporter=verbose runs the two test files.

Fake timers control timer callbacks. Mock the I/O if a test needs to avoid a real network or disk wait.