Skip to the page

Testing React components · mid

user-event, findBy, waitFor and act warnings

Simulate users with user-event (await user.click / user.type after userEvent.setup()), wait for UI that appears later with findBy, use waitFor only for assertions that need retrying, and treat 'not wrapped in act(...)' warnings as a sign that state changed after your test stopped watching.

The notes

What you must know

  • const user = userEvent.setup(); await user.type(input, 'piz'); await user.click(button). user-event fires the full sequence (pointer, focus, keydown, input, keyup), so it catches more bugs than fireEvent.
  • findBy* = getBy* + waitFor. Prefer await screen.findByRole('alert') over await waitFor(() => screen.getByRole('alert')).
  • waitFor rules: put one assertion inside; no side effects (clicks) inside, because it runs the callback many times; never pass an empty callback.
  • waitForElementToBeRemoved for spinners; or expect(screen.queryByRole('progressbar')).not.toBeInTheDocument() after awaiting the result.
  • act() warnings mean React state updated outside an awaited test step (a promise resolved after the test ended or between steps). Fix by awaiting the UI result (findBy), not by wrapping random code in act.
  • With fake timers, pass advanceTimers to userEvent.setup.

The red pen

Common traps: mistake → fix

  • Mistake: "fireEvent.change is the same as typing"

    Fix: it fires one event; real typing has focus, key and input events per character.

  • Mistake: "Wrap everything in act to silence the warning"

    Fix: the warning points to an unawaited update; await the outcome instead.

  • Mistake: "Click inside waitFor until it works"

    Fix: waitFor retries the callback, so the click may run many times.

Easy to hard

Questions interviewers ask, easy to hard

  1. userEvent vs fireEvent?
  2. How do you test UI that appears after an API call?
  3. What does 'An update was not wrapped in act(...)' mean and how do you fix it properly?
  4. Test the debounced autocomplete: typing, results, keyboard selection and an out-of-order response.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview