Skip to content

Conversation

TrevorBurnham
Copy link

This PR adds automatic detection of fake timers from both Jest and Vitest, eliminating the need for users to manually configure advanceTimers when using vi.useFakeTimers() or jest.useFakeTimers().

Fixes #1115

Problem

When using Vitest with fake timers, userEvent would timeout because it wasn't advancing the fake timers. Users had to use workarounds like:

globalThis.jest = {
  advanceTimersByTime: vi.advanceTimersByTime.bind(vi),
}

This happened because userEvent only knew about Jest's timer APIs, not Vitest's.

Solution

Automatic detection of both Jest and Vitest fake timers:

  1. New timerDetection.ts utility - Detects which testing framework's fake timers are active by checking for globalThis.jest or globalThis.vi
  2. Updated wait.ts - When advanceTimers isn't manually configured, automatically detects and uses the appropriate timer advancement function
  3. Fully backward compatible - Manual configuration still takes precedence over auto-detection

When both Jest and Vitest globals are present (unlikely but possible), Jest takes precedence. This maintains consistency with existing behavior.

Before

test('button click', async () => {
  vi.useFakeTimers()
  globalThis.jest = {
    advanceTimersByTime: vi.advanceTimersByTime.bind(vi),
  }
  const user = userEvent.setup()
  await user.click(button) // Would timeout without workaround
})

After

test('button click', async () => {
  vi.useFakeTimers()
  // No workaround needed! ✨
  const user = userEvent.setup()
  await user.click(button) // Works automatically
})

Copy link

codesandbox-ci bot commented Oct 5, 2025

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

userEvent.click() fails when used with vi.useFakeTimers(), all available solutions are not working
1 participant