Skip to content
FrontDepth, Home

Testing

Testing UI the way users use it

How to test components the way people use them: Testing Library's guiding principle and query priority, getBy, queryBy and findBy, user-event instead of fireEvent, jest-dom assertions on what users perceive, a form example, what jsdom cannot show, and tests that break for the wrong reasons.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

Test what the user sees and does

Testing Library is built around one sentence by its author, Kent C. Dodds: "The more your tests resemble the way your software is used, the more confidence they can give you." A component has two kinds of users: the person who sees and clicks it, and the developer who renders it with props. A UI test should deal with the component the way they do: find elements by what they show, interact the way a person would, and check what ends up on the screen.

Everything else (state variables, hooks, component instances, CSS class names) is what Kent C. Dodds calls implementation details: "things which users of your code will not typically use, see, or even know about." Tests built on them fail in both directions. They break when you refactor, for example when useState becomes useReducer, although nothing changed for the user. And they keep passing when the button on the screen no longer does anything.

A first component test

A common stack for React: Vitest runs the tests in a simulated browser environment (jsdom or happy-dom), React Testing Library renders the component, @testing-library/user-event plays the user, and @testing-library/jest-dom adds matchers for the DOM.

TSX
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test } from "vitest";
import { QuantityPicker } from "./QuantityPicker";

test("increases the quantity", async () => {
  const user = userEvent.setup();
  render(<QuantityPicker initial={1} />);

  await user.click(screen.getByRole("button", { name: "Increase quantity" }));

  expect(screen.getByText("Quantity: 2")).toBeInTheDocument();
});
  • render mounts the component into a div that it appends to document.body.
  • screen holds every query, bound to document.body. Testing Library recommends it over the queries that render returns.
  • The test reads like a manual check: find the button by its role and name, click it, look for the new text. It does not know whether the count lives in useState, a reducer or a store.

In Kent C. Dodds' classification, a test of one component like this is a unit test. The same tools also render whole pages with the network mocked, which he counts as . Either way, the test runs in a simulated browser, not a real one.

Setup that is easy to miss

After each test, cleanup unmounts what render mounted. React Testing Library registers it automatically only when the test runner provides a global afterEach. Vitest does not by default, so either set globals: true or call cleanup() in an afterEach in a setup file. The same setup file imports @testing-library/jest-dom/vitest, which adds matchers such as toBeInTheDocument to Vitest's expect. Without cleanup, the previous test's DOM stays in the document, and the next test finds two of everything.

JuniorConcept

Finding elements: the query priority

Testing Library's queries find elements the way people do. Its docs recommend this order:

  1. Queries accessible to everyone. getByRole ("your top preference for just about everything"), getByLabelText for form fields, getByPlaceholderText when a field has nothing better, getByText for non-interactive content, getByDisplayValue for filled-in fields.
  2. Semantic queries. getByAltText and getByTitle. The docs warn that title is not read consistently by screen readers and is not visible to sighted users by default.
  3. Test IDs. getByTestId, only when nothing else fits: users can neither see nor hear a data-testid.
TSX
screen.getByRole("heading", { name: "Order summary" });
screen.getByRole("button", { name: /place order/i });
screen.getByRole("checkbox", { name: "Gift wrap" });
screen.getByLabelText("Promo code");
screen.getByText("Free delivery on orders over $50");

Why role queries also test accessibility

getByRole(role, { name }) searches the accessibility tree, the same information a screen reader uses. The role comes from the element (<button> is a button without any role attribute), and the name is its : a button's text, a field's label, an aria-label. If getByRole("button", { name: "Close" }) cannot find an icon-only close button, a screen reader user hears an unnamed "button" too, and the test has found a real bug. When a role query fails, the error lists the accessible roles and names that it did find, which is often enough to see the problem. How browsers compute names is covered in the topic on ARIA and focus.

One exception to know: <input type="password"> has no implicit role, so find it with getByLabelText.

Matching text

A string matches the whole text, case-sensitively, after trimming and collapsing whitespace. A regular expression matches part of it: /place order/i survives "Place order" becoming "Place order now". { exact: false } gives a case-insensitive substring match, but the docs prefer a regex for fuzzy matching. getByText compares only an element's own text nodes, so <p>Total: <strong>$40</strong></p> does not match "Total: $40". Query an element that has a role and name instead, or check the paragraph's text with toHaveTextContent.

To search inside one part of the page, scope the queries with within:

TSX
const cart = screen.getByRole("list", { name: "Cart" });
expect(within(cart).getAllByRole("listitem")).toHaveLength(2);
JuniorConcept

getBy, queryBy and findBy

Every query comes in three forms, and the prefix decides what happens when the element is not there:

QueryNo matchOne matchMore than oneWaits
getBy...throwsreturns itthrowsno
queryBy...returns nullreturns itthrowsno
findBy...rejectsresolves with itrejectsyes, 1000 ms by default

Each has an All version for lists: getAllBy... throws when nothing matches, queryAllBy... returns [], and findAllBy... waits for at least one match.

Which one to use

  • getBy by default. It fails on the line where the element is missing, with a message that prints the current DOM.
  • queryBy only to prove that something is absent:
TSX
expect(screen.queryByRole("alert")).not.toBeInTheDocument();

getByRole("alert") here would throw before expect even runs. The opposite mistake, queryBy for something that must be there, works but fails with a poor message. Kent C. Dodds' advice is to "only use the query* variants for asserting that an element cannot be found".

  • findBy for elements that appear later: after a request, a timer or an effect. It returns a promise, so it must be awaited:
TSX
await user.click(screen.getByRole("button", { name: "Load more" }));
expect(await screen.findAllByRole("article")).toHaveLength(20);

findBy is getBy combined with waitFor: it retries until the query succeeds or the timeout passes. The topic on async and flaky tests covers waiting in depth.

"Found multiple elements"

getBy, queryBy and findBy throw when more than one element matches. That is a feature: a test that clicks "Remove" on a page with five "Remove" buttons should say which one. Narrow the query by name ({ name: "Remove Rain jacket" }) or scope it with within. Do not reach for getAllByRole("button")[0] to silence the error: the test then clicks whichever element happens to come first, and a change in order makes it click another one.

If the duplicate comes from markup that the current test never rendered, the previous test's DOM is still in the document: cleanup is not running.

MiddleFramework

user-event instead of fireEvent

Testing Library has two ways to interact. fireEvent dispatches one DOM event: fireEvent.click(button) creates a click event and nothing else. The user-event docs call fireEvent "a lightweight wrapper around the browser's low-level dispatchEvent API", while user-event "allows you to describe a user interaction instead of a concrete event". A real click moves the pointer onto the element, presses and releases the mouse button and focuses the element before click fires. Typing focuses the field, then fires keyboard and input events for every character while the value and the selection change. user-event also refuses what a browser would refuse: it does not type into a disabled field, and it will not click an element with pointer-events: none.

TSX
test("adds a tag on Enter", async () => {
  const user = userEvent.setup();
  render(<TagInput />);

  const input = screen.getByRole("textbox", { name: "New tag" });
  await user.type(input, "urgent{Enter}");

  expect(screen.getByRole("listitem")).toHaveTextContent("urgent");
  expect(input).toHaveValue("");
});

The same test with fireEvent needs fireEvent.change(input, { target: { value: "urgent" } }) and then fireEvent.keyDown(input, { key: "Enter" }), which ties it to the event the component happens to listen to. user-event also does what Enter does in a form field: it clicks the form's submit button, or submits a form whose only field is this one. So the user-event test keeps passing if the component moves from an onKeyDown handler to a <form onSubmit>, while the fireEvent.keyDown version breaks although users see no change. In the other direction, fireEvent.change never focuses or blurs the field, so a "validate when the field loses focus" rule is never exercised; await user.tab() is.

Using it

  • Call userEvent.setup() at the start of the test, before render. The docs discourage calling user-event or rendering in beforeEach and other hooks.
  • Every method returns a promise. await each call, or the next line runs before the interaction has finished.
  • Methods you will use most: click, dblClick, hover, type (clicks the field first), keyboard("{Shift>}{Tab}{/Shift}"), tab(), clear, selectOptions for a <select>, and upload for a file input.

fireEvent is still the tool for events that user-event does not model, such as scroll, or for one low-level event your code really depends on. For interactions user-event cannot describe yet, its docs suggest fireEvent to dispatch "the concrete events that your software relies on". The price is that the test then encodes your assumptions about which events a real interaction fires.

MiddleConcept

Assert on what the user can perceive

The end of a test should check the result the user gets: text on the screen, a field's value, a disabled button, where focus is. jest-dom provides matchers for exactly that:

  • toBeInTheDocument(): the element is attached to the document.
  • toHaveTextContent(text): with a string this is a substring match, so toHaveTextContent("$4") passes for "Total: $40". Use a regex such as /^Total: \$40$/ to match the whole text.
  • toBeVisible(): the element is in the document; neither it nor any ancestor has display: none, visibility: hidden or collapse, opacity: 0 or the hidden attribute; and a closed <details> hides its content.
  • toBeDisabled() and toBeEnabled(): the disabled attribute, including one inherited from a disabled <fieldset>. They ignore aria-disabled.
  • toHaveValue(), toHaveDisplayValue() and toBeChecked(): form state.
  • toHaveFocus(): where keyboard focus is.
  • toHaveAccessibleName() and toHaveAccessibleDescription(): what assistive technology announces for a control.
  • toBeInvalid(): aria-invalid="true", or the browser's own constraint validation failing.

These matchers also fail better than expect(button.disabled).toBe(true): the message shows the element instead of "expected false to be true".

What not to assert

  • State and internals: the value inside useState, a reducer's state, how many times a component rendered, which hook was called.
  • Props passed to children, or a child component replaced by a stub so the test can inspect what it received.
  • Class names and markup structure, unless they are the only way the user could notice the difference.

React Testing Library has rerender(<Price amount={20} />) for updating props, but its docs suggest testing the component that does the prop updating instead, because that is how the value really changes.

Callbacks are outputs

A callback prop is part of the component's contract with its parent, so checking it with a function tests behaviour, not internals:

TSX
const onInvite = vi.fn();
render(<InviteForm onInvite={onInvite} />);
await user.type(screen.getByRole("textbox", { name: "Email" }), "ana@example.com");
await user.click(screen.getByRole("button", { name: "Send invite" }));
expect(onInvite).toHaveBeenCalledWith("ana@example.com");

A useful question before every assertion: could a user, or the parent component, observe this? If the only way to notice a change is to read the component's internals, the test is checking an implementation detail.

MiddleExample

Example: a form with a validation message

An invite form has one email field and a "Send invite" button. An invalid address shows an error under the field; a valid one calls onInvite.

TSX
export function InviteForm({ onInvite }: { onInvite: (email: string) => void }) {
  const [error, setError] = useState("");

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const email = String(new FormData(event.currentTarget).get("email")).trim();
    if (!email.includes("@")) {
      setError("Enter a valid email address");
      return;
    }
    setError("");
    onInvite(email);
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label htmlFor="invite-email">Email</label>
      <input id="invite-email" name="email" type="email" aria-invalid={error !== ""}
        aria-describedby={error ? "invite-error" : undefined} />
      {error && <p id="invite-error">{error}</p>}
      <button type="submit">Send invite</button>
    </form>
  );
}
TSX
test("rejects an address without @", async () => {
  const user = userEvent.setup();
  const onInvite = vi.fn();
  render(<InviteForm onInvite={onInvite} />);

  const email = screen.getByRole("textbox", { name: "Email" });
  await user.type(email, "ana.example.com");
  await user.click(screen.getByRole("button", { name: "Send invite" }));

  expect(email).toHaveAttribute("aria-invalid", "true");
  expect(email).toHaveAccessibleDescription("Enter a valid email address");
  expect(onInvite).not.toHaveBeenCalled();
});

The second test types ana@example.com, submits, and checks expect(onInvite).toHaveBeenCalledWith("ana@example.com") and that queryByText("Enter a valid email address") is not in the document.

What these tests get right:

  • The field is found by its label and the button by its name, so a missing <label> or an unnamed button fails the test.
  • toHaveAccessibleDescription checks that the message is connected to the field through aria-describedby, so a screen reader announces it with the field. getByText("Enter a valid email address") would also pass with the message sitting on the page unconnected.
  • aria-invalid is checked directly: it is the state assistive technology reports. toBeInvalid() would also pass when only the browser's validation fails, because it counts checkValidity() too.
  • Both paths are covered, and the valid path also checks that no error appears. One more test is worth writing: fix the address after an error and check that the message goes away.
  • noValidate turns off the browser's built-in validation, so the form's own message, the one the tests check, is what users see.

If the form validated when the field loses focus, the test would leave the field with await user.tab() instead of submitting.

SeniorWeb platform

What jsdom cannot tell you

Vitest's jsdom and happy-dom environments implement the DOM and many browser APIs in Node. They are fast and good enough for most component behaviour, but they are not browsers. jsdom's README says it plainly: it "does not do any layout or rendering".

  • No layout. getBoundingClientRect(), offsetWidth and offsetTop return zeros, nothing scrolls, and window.scrollTo only reports "not implemented". Code that measures elements, positions a tooltip or virtualises a list cannot be checked.
  • No real CSS. By default Vitest replaces imported CSS files with empty strings (its css.include option is empty), so your stylesheet never reaches the document. toBeVisible() then sees only inline styles and the hidden attribute: a panel hidden by .is-collapsed { display: none } counts as visible. Hover styles, media queries, :focus-visible and stacking order do not exist either.
  • No hit testing. user-event's docs point out that elements have no position or size in jsdom, so it does not check whether a pointer action is possible there: it clicks a button that an overlay covers in the real page.
  • Missing APIs. jsdom has no IntersectionObserver, ResizeObserver or matchMedia. You can stub them, but then the test checks your stub. happy-dom is faster but, in Vitest's words, "lacks some API".
TSX
test("opens the answer", async () => {
  const user = userEvent.setup();
  render(<Faq />);
  const question = screen.getByRole("button", { name: "Shipping times" });
  await user.click(question);

  expect(question).toHaveAttribute("aria-expanded", "true");
  // Passes in jsdom even if a CSS class still hides the answer in a browser
  expect(screen.getByText(/ships within/i)).toBeVisible();
});

Assert on what jsdom can see: the aria-expanded state, the hidden attribute, the text. Do not take a toBeVisible() pass as proof that CSS shows the element.

When to use a real browser

Keep jsdom tests for logic and behaviour: what renders, what a click changes, what a form sends. Move a check to a real browser when it depends on layout, scrolling, CSS deciding visibility, focus styles, drag and drop, or browser APIs jsdom lacks. Vitest's Browser Mode runs component tests in a real browser through Playwright or WebdriverIO, and an with Playwright drives the whole app. Vitest's docs explain why: simulated environments "may result in some discrepancies", and "false positives or negatives in test results may occur". Queries by role and label exist in both, so the habits carry over.

One cost to know: getByRole is the slowest query on a large DOM, because it computes roles and checks visibility. The docs suggest { hidden: true } where speed matters, which skips the visibility checks but also returns inaccessible elements, so use it deliberately.

SeniorPitfalls

Tests that break for the wrong reasons, or never fail

Two kinds of UI test cost the most: those that fail when nothing is wrong for the user, and those that pass when something is.

Failing for the wrong reasons

  • Querying by CSS class or DOM structure: container.querySelector(".btn-primary"), container.firstChild. React Testing Library's docs say that if you find yourself using container to query for elements, you should reconsider. A restyle breaks such a test; a broken button does not.
  • A whole-tree snapshot as the main assertion. Every markup change fails it, and reviewers learn to accept updated snapshots without reading them.
  • Long exact strings. getByText("Your order #1042 has been placed and will ship within 2 business days") breaks on every copy edit. Match the stable part with a regex, or query the element by role.
  • Stubbed child components that render a placeholder so the parent can be tested alone. The test then checks the wiring between stubs, not what users get.

Never failing

  • Test IDs everywhere. getByTestId("submit") still passes after the button loses its visible label or turns into a div that the keyboard cannot reach.
  • ARIA added for the test. Putting role="button" on a div so that getByRole finds it makes the query pass and misleads screen reader users: the div still has no keyboard support. Use a real <button>.
  • Assertions that hold before anything happens. expect(screen.queryByText("Something went wrong")).not.toBeInTheDocument() after a click without await passes because the click has not finished yet.
  • act around everything. render, fireEvent and user-event are already wrapped in act. Extra wrappers only add noise; Kent C. Dodds lists them among the common mistakes.

Make it fail once

Before you trust a new test, break the code on purpose: remove the click handler, change the error text, drop the <label>. A test that stays green has no value. eslint-plugin-testing-library catches many of these patterns automatically, with rules such as no-container, no-node-access, prefer-screen-queries, prefer-find-by and no-unnecessary-act.

A green UI test is a claim about what users can do. Make sure it can be false.

SeniorInterview tips

Interview tips

A 30-second answer. "I test components the way a user uses them: render, find elements by role and accessible name or by label, interact with user-event, and assert on what is on the screen with jest-dom. I avoid state, class names and test IDs, so a refactor does not break the tests and a broken UI does. getBy is my default, queryBy only to prove absence, findBy for what appears later. And I know jsdom's limits: no layout and no real CSS, so behaviour that depends on them goes to a browser test."

Questions you are likely to get

  • Which query would you use for this button? getByRole("button", { name }). Explain the priority, and that a failing role query often means an accessibility bug.
  • getBy, queryBy or findBy? Throws, returns null, waits (1000 ms by default). Name the case for each.
  • Why user-event and not fireEvent? A full interaction instead of one event: focus, keyboard events, Enter submitting a form, no typing into disabled fields.
  • How do you test a form? Type and submit like a user, check the message and its connection to the field, check the callback, cover both the valid and the invalid path.
  • What is an implementation detail? Kent C. Dodds' definition, an example, and the two failure modes: breaking on refactors and passing when the app is broken.
  • What can't a jsdom test tell you? Layout, real CSS, scrolling, observers, whether an element is covered.

Mistakes that cost points

  • Answering "I'd add a data-testid" before thinking about roles and labels.
  • Asserting on component state, or querying with container.querySelector.
  • fireEvent for typing, or user-event calls without await.
  • Treating a jsdom toBeVisible() pass as proof that the user sees the element.

Senior signal

Talk about the test suite as a product. Role and label queries double as cheap accessibility checks. A shared render helper built on render's wrapper option keeps providers out of every test. eslint-plugin-testing-library in CI stops the usual mistakes before review. There is a clear rule for what moves to Browser Mode or Playwright. And show you know the trade-offs: role queries are slow on huge trees, which is a reason to render smaller trees in tests, not to fall back to test IDs.

JuniorReview checklist

What to check when reviewing UI tests

Use this list on component tests you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. A UI test that leans on implementation details breaks on every refactor and still lets real bugs through.

  • Are elements found by role and accessible name, or by label, before text and test IDs? Search the diff for getByTestId, container.querySelector and class selectors; each needs a reason. A role query also catches a control that screen readers cannot name.
  • Is every interaction done with user-event and awaited? Look for fireEvent.change used for typing and for user. calls without await; a missing await lets the assertion run before the interaction has finished.
  • Does each query prefix match its intent? getBy for what must be there, queryBy only with not.toBeInTheDocument(), an awaited findBy for what appears later. getAllBy(...)[0] hides an ambiguous query.
  • Do the assertions check what the user perceives? Text, values, focus, disabled state and accessible descriptions through jest-dom, not state, render counts or child props. Remember that toHaveTextContent with a string matches a substring.
  • Does the test fail when the feature breaks? Break the code locally (remove the handler, drop the label) and run it; a test that stays green checks nothing.
  • Are cleanup and the matchers set up? In Vitest: globals: true or a setup file that calls cleanup() in afterEach, plus @testing-library/jest-dom/vitest. "Found multiple elements" errors that come and go often mean DOM left over from another test.
  • Does any assertion depend on layout or CSS? toBeVisible() with class-based hiding, measurements and scrolling pass or fail for the wrong reasons in jsdom; those checks belong in a browser test.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions