Lesson 10 of 11 · 12 min · Testing React

Testing user events and asynchronous UI

Covers: Vitest with React Testing Library and user-event on React 19. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • Simulate users with @testing-library/user-event
  • Test clicks, typing, selects, checkboxes, keyboard use and tabbing
  • Wait for asynchronous changes with findBy and waitFor
  • Test a whole form, including validation messages
  • Avoid act warnings and flaky tests, and use fake timers

In simple words

A real user does not set state; they click, type and press keys, and the screen changes. A good test does the same. A user-event library performs those actions in the pretend browser in a realistic order (moving, pressing, releasing, focusing), so your component reacts as it would for a person. Some changes happen a moment later, after a delay or a network call, so the test must wait for them instead of checking too early.

Words to know

  • user-event: a library that simulates realistic user interactions in tests.
  • Asynchronous UI: screen changes that happen later, such as after a request finishes.
  • act: the React helper that makes sure all updates from an action are applied before you assert.
  • Flaky test: a test that sometimes passes and sometimes fails without any code change.

user-event

@testing-library/user-event (version 14 and later) simulates a user far better than the low-level fireEvent. A click through user-event triggers pointer events, focus, mousedown, mouseup and click in order; typing fires key events and input for every character.

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi } from "vitest";
import { Counter } from "./Counter";

describe("Counter", () => {
  it("increments when the button is clicked", async () => {
    const user = userEvent.setup();                       // create one per test, before rendering
    render(<Counter />);

    expect(screen.getByText("Count: 0")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: /increment/i }));
    await user.click(screen.getByRole("button", { name: /increment/i }));

    expect(screen.getByText("Count: 2")).toBeInTheDocument();
  });
});

Key points:

  • Call userEvent.setup() first, then use user.click(...) and the others. All user-event methods are asynchronous, so await them.
  • After an awaited interaction, React has already processed the updates, so you can assert immediately (the library wraps events in act for you).

Common interactions:

await user.click(element);
await user.dblClick(element);
await user.hover(element);                  // and user.unhover
await user.type(screen.getByLabelText("Email"), "asha@example.com");     // clicks, then types each key
await user.clear(input);
await user.selectOptions(screen.getByLabelText("Target job"), "data-analyst");
await user.click(screen.getByRole("checkbox", { name: /agree/i }));      // toggles a checkbox
await user.upload(fileInput, new File(["cv"], "cv.pdf", { type: "application/pdf" }));
await user.keyboard("{Enter}");             // keys: {Escape}, {Tab}, {ArrowDown}, {Shift>}a{/Shift}
await user.tab();                           // move focus like the Tab key
await user.paste("copied text");

Special characters in type need escaping: {{ for a literal brace and [[ for a bracket, and {Enter} presses Enter (so await user.type(input, "hello{Enter}") types and submits).

Testing a form

function LoginForm({ onSubmit }: { onSubmit: (v: { email: string; password: string }) => void }) {
  const [error, setError] = useState("");
  function handle(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    const email = String(data.get("email"));
    const password = String(data.get("password"));
    if (password.length < 8) { setError("Use at least 8 characters."); return; }
    setError("");
    onSubmit({ email, password });
  }
  return (
    <form onSubmit={handle}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" />
      <label htmlFor="password">Password</label>
      <input id="password" name="password" type="password" />
      {error && <p role="alert">{error}</p>}
      <button type="submit">Sign in</button>
    </form>
  );
}
describe("LoginForm", () => {
  it("submits the entered values", async () => {
    const user = userEvent.setup();
    const handleSubmit = vi.fn();                         // a mock function records its calls
    render(<LoginForm onSubmit={handleSubmit} />);

    await user.type(screen.getByLabelText("Email"), "asha@example.com");
    await user.type(screen.getByLabelText("Password"), "correct-horse");
    await user.click(screen.getByRole("button", { name: "Sign in" }));

    expect(handleSubmit).toHaveBeenCalledTimes(1);
    expect(handleSubmit).toHaveBeenCalledWith({ email: "asha@example.com", password: "correct-horse" });
  });

  it("shows an error and does not submit a short password", async () => {
    const user = userEvent.setup();
    const handleSubmit = vi.fn();
    render(<LoginForm onSubmit={handleSubmit} />);

    await user.type(screen.getByLabelText("Password"), "short");
    await user.click(screen.getByRole("button", { name: "Sign in" }));

    expect(screen.getByRole("alert")).toHaveTextContent("Use at least 8 characters.");
    expect(handleSubmit).not.toHaveBeenCalled();
  });
});

This is a good template: arrange with render, act with user, assert on visible results and on the callback. Because the test finds fields by label, it fails if a label is missing, protecting accessibility.

Asynchronous UI

Sometimes the screen changes later: after a timer, a promise, or a mocked request. You must wait, or the assertion runs too early.

  • findBy... = getBy + waiting (default timeout 1000 ms, polling): the normal tool for "an element should appear".
await user.click(screen.getByRole("button", { name: "Load orders" }));
expect(await screen.findByText("Order 101")).toBeInTheDocument();         // waits until it appears
  • waitFor(callback) retries a callback until it stops throwing; use it for assertions that are not "an element appears" (for example a mock call or a changed attribute):
import { waitFor } from "@testing-library/react";
await waitFor(() => expect(saveOrder).toHaveBeenCalledWith({ id: 101 }));
  • waitForElementToBeRemoved waits until an element disappears (a spinner):
await waitForElementToBeRemoved(() => screen.queryByText("Loading..."));

Rules to avoid flakiness:

  • Never put several assertions with side effects inside waitFor, and do not put user actions inside it (it may run the callback many times).
  • Prefer findBy over waitFor + getBy when you wait for an element.
  • Do not use setTimeout/sleep in tests to "wait a bit".
  • Assert what the user would see (a message, a disabled button), not internal state.
  • Do not call getBy for something that appears later (it throws immediately).

act warnings

React warns "An update to X inside a test was not wrapped in act(...)" when state updates happen outside the test's awareness. With Testing Library and await user... / findBy / waitFor, act is handled for you. If you see the warning, it usually means something updates after your test finished or you asserted too early: await the pending work (findBy), or make sure the async operation is awaited or cancelled before the test ends. Avoid wrapping in act by hand unless you call React APIs directly.

Keyboard and accessibility

Test that the interface works without a mouse:

it("opens the menu with Enter and closes it with Escape", async () => {
  const user = userEvent.setup();
  render(<Menu />);

  await user.tab();                                                     // focus the first focusable element
  expect(screen.getByRole("button", { name: "Menu" })).toHaveFocus();

  await user.keyboard("{Enter}");
  expect(screen.getByRole("menu")).toBeVisible();

  await user.keyboard("{Escape}");
  expect(screen.queryByRole("menu")).not.toBeInTheDocument();
});

Check names, roles, aria-expanded, focus management after opening a dialog and returning focus after closing it. You can add automated checks with jest-axe (vitest-axe): expect(await axe(container)).toHaveNoViolations(), which catches many issues (missing labels, contrast is not testable in jsdom) but not all.

Timers and dates

Components using setTimeout, setInterval, debounce or the current date become slow or flaky to test. Use fake timers:

import { vi, beforeEach, afterEach } from "vitest";

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

it("searches 300 ms after typing stops", async () => {
  const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });   // let user-event cooperate with fake timers
  const onSearch = vi.fn();
  render(<SearchBox onSearch={onSearch} />);

  await user.type(screen.getByRole("searchbox"), "java");
  expect(onSearch).not.toHaveBeenCalled();

  await vi.advanceTimersByTimeAsync(300);
  expect(onSearch).toHaveBeenCalledWith("java");
});

vi.setSystemTime(new Date("2025-10-31T10:00:00+05:30")) fixes the date. Remember to restore real timers after each test (afterEach), or later tests hang.

Testing hooks and components that call callbacks

  • A custom hook can be tested with renderHook from Testing Library: const { result } = renderHook(() => useToggle()); act(() => result.current.toggle()); expect(result.current.on).toBe(true);. Prefer testing hooks through a component when you can.
  • For callback props, pass vi.fn() and assert toHaveBeenCalledWith; for components that navigate, wrap with MemoryRouter and assert on the rendered next page.

Flaky test checklist

Symptom Likely cause and fix
Passes alone, fails in the suite shared state, missing cleanup, modules with state: reset mocks and use fresh providers per test
Sometimes cannot find an element missing await or findBy; the data had not arrived
"Unable to find role" wrong accessible name; use screen.debug() and logRoles
Timeouts forgot vi.useRealTimers(), or fake timers not advanced, or a promise never resolves
act warnings work finishing after the test; await it
Differences between machines dates, time zones, random values, locale: fix the inputs

Common mistakes

  • Forgetting await on user calls.
  • Using fireEvent for everything instead of user-event.
  • Using getBy for async content.
  • Actions or many assertions inside waitFor.
  • sleep instead of waiting for the condition.
  • Not restoring fake timers.
  • Testing only the click and not the outcome.

Try it yourself

  1. Test a counter with user.click and assert the visible count.
  2. Test the login form with valid input, an invalid password and an empty form.
  3. Add a component that shows "Loading..." then data after a timer; wait with findByText.
  4. Test keyboard operation of a menu with user.tab() and user.keyboard.
  5. Test a debounced search with fake timers.

Check yourself

Why prefer user-event to fireEvent?

user-event simulates the full sequence of events a real user causes (focus, pointer, key presses), so tests match real behaviour more closely, while fireEvent dispatches a single low-level event.

When do you use findBy instead of getBy?

When the element appears asynchronously; findBy waits and retries until it appears or times out, while getBy fails immediately.

Why are user-event calls awaited?

They are asynchronous, simulating the timing of real interactions; awaiting ensures the interaction and React's updates finish before you assert.

How do you test code that uses setTimeout?

Use fake timers (vi.useFakeTimers()) and advance them (vi.advanceTimersByTime), restoring real timers after the test.

Interview questions

How do you test that a form shows validation errors and submits valid data?

Render it, use user.type and user.click to fill and submit, assert that error messages (found by role alert or text) appear for invalid input and that the submit callback was not called, then repeat with valid input and assert the callback arguments.

What causes flaky tests in React UIs and how do you fix them?

Not waiting for async updates, shared state between tests, real timers and dates, random data, and network calls; fix with findBy and waitFor, per-test setup and cleanup, fake timers and fixed dates, and mocked network.

What is the act warning?

React warns when a state update happens outside the test harness's awareness, usually because async work completes after assertions; await the work with findBy/waitFor so the update is observed.

Summary

  • user-event simulates real, asynchronous interaction; create it with setup() and await every call.
  • Use findBy and waitFor for async UI; avoid sleeps; do not put actions in waitFor.
  • Test forms, validation, keyboard use and focus; add automated accessibility checks.
  • Use fake timers and fixed dates for time-based code; isolate tests to avoid flakiness.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.