Testing Library

Also known as: React Testing Library

On this page 7

Testing Library is a family of open-source JavaScript utilities for testing user interface components by querying the rendered DOM the way a user perceives it, through visible text, labels and accessible roles rather than internal component state. In Web testing, it occupies the layer between pure unit tests and full browser automation, and its best-known package, React Testing Library, has become the default choice for component tests in many React projects.

The project is built around one guiding principle: the more tests resemble the way software is used, the more confidence they give. Instead of inspecting props, instance methods or private state, a test renders a component, finds elements as a person or a screen reader would, simulates interaction and asserts on the visible result. Tests written this way survive refactoring because they depend on behavior, not on implementation details.

How Testing Library works inside a test runner

Testing Library is not a test runner and not a browser. It is a set of helpers that run inside a runner such as Jest, Vitest or Mocha, usually against a simulated DOM like jsdom or happy-dom. The framework adapter renders a component into a detached container attached to document.body, and the shared core, DOM Testing Library, supplies the queries that search that container.

A typical test follows a fixed sequence. It renders the component, locates elements with queries such as getByRole or getByLabelText, triggers events through the companion package user-event, and asserts on the outcome, often with matchers from jest-dom such as toBeVisible or toHaveAccessibleName. Asynchronous updates are handled with findBy queries and waitFor, which poll the DOM until a condition holds or a timeout expires, by default after about one second.

The table below lists the main packages and the role each plays in a test setup.

PackagePurposeTypical use
DOM Testing LibraryFramework-agnostic queries and utilitiesBase for all adapters, plain DOM code
React Testing LibraryRenders React components into the DOMComponent tests in React projects
user-eventSimulates realistic input sequencesTyping, clicking, tabbing, pasting
jest-domCustom DOM assertion matchersChecks for visibility, state and attributes
Vue, Angular and Svelte adaptersFramework-specific render functionsComponent tests outside React
Core packages of the Testing Library family

Query types and their priority order

Queries are the heart of Testing Library, and the project documents an explicit priority order that favors what users and assistive technologies can perceive. The highest-ranked query, getByRole, finds elements through the accessibility tree, using ARIA roles and accessible names computed according to the WAI-ARIA and accessible name specifications. Test IDs sit at the bottom of the list as an escape hatch of last resort.

The following table summarizes the recommended order and the reasoning behind each tier.

QueryWhat it matchesWhen to use it
getByRoleRole plus accessible nameDefault for buttons, links, headings, inputs
getByLabelTextForm control by its labelForm fields with visible labels
getByPlaceholderTextPlaceholder attributeOnly when no label exists
getByTextVisible text contentNon-interactive content such as messages
getByDisplayValueCurrent value of a fieldPrefilled or edited form values
getByAltText and getByTitleAlt text or title attributeImages and rare titled elements
getByTestIddata-testid attributeElements with no accessible handle
Recommended query priority

Each query also comes in three variants with different failure behavior. The choice between them determines whether a missing element throws immediately, returns nothing or is awaited.

VariantNo matchMultiple matchesAsync
getByThrows an errorThrows an errorNo
queryByReturns nullThrows an errorNo
findByRejects after timeoutRejectsYes, returns a promise
getAllBy, queryAllBy, findAllByThrow, empty array, rejectReturn an arrayOnly findAllBy
Query variants and their behavior

How Testing Library compares with other web testing tools

Testing Library is best understood as a component and integration testing layer, not a replacement for end-to-end tools. It runs in a simulated DOM, so it is fast, typically milliseconds per test, but it cannot verify layout, real rendering, network behavior or cross-browser differences. Browser automation tools cover those gaps at the cost of speed and setup complexity.

ApproachEnvironmentMain strengthMain limitation
Testing Libraryjsdom or happy-dom in Node.jsFast, behavior-focused component testsNo real layout or CSS rendering
Enzyme-style shallow renderingVirtual component treeIsolates a single componentCouples tests to implementation
Playwright or CypressReal browser enginesFull end-to-end user flowsSlower and harder to stabilize
Visual regression toolsReal browser screenshotsDetects visual changesNo behavioral assertions
Testing Library and related approaches

The query philosophy has spread beyond the library itself. Playwright offers role-based locators modeled on the same idea, and an extension package brings Testing Library queries into Cypress, so teams can share one selector vocabulary across test layers.

Writing reliable tests with Testing Library

Reliable tests depend on a small number of disciplined habits. The most important one is to assert on observable output: rendered text, element states, announced messages and calls to mocked network boundaries, rather than on how a component stores data internally.

  • Prefer user-event over fireEvent, because it dispatches the full sequence of pointer, focus and keyboard events a real interaction produces.
  • Use the screen object for queries instead of destructuring results from render, which keeps tests consistent and readable.
  • Mock at the network boundary, for example with a request interception library, instead of mocking child components.
  • Await findBy queries for content that appears after asynchronous work instead of adding arbitrary delays.
  • Treat a hard-to-write getByRole query as a signal of an accessibility defect in the component, not as a reason to add a test ID.

Limitations and common mistakes

Testing Library inherits the limits of the simulated DOM. jsdom does not compute layout, so properties such as element size, scroll position and CSS-driven visibility are unreliable, and features such as IntersectionObserver or matchMedia must be mocked. Many recurring problems stem from misuse rather than from the library itself, as the table shows.

SymptomLikely causeFix
act() warnings in the consoleState updates after the test finishedAwait findBy or waitFor for pending updates
Tests break after refactoringAssertions on internal state or class namesAssert on text, roles and visible behavior
Slow getByRole queriesLarge DOM trees with complex rolesNarrow scope with within() or simplify markup
Flaky asynchronous testsSide effects inside waitFor callbacksKeep only assertions inside waitFor
Overuse of data-testidInaccessible componentsAdd labels and roles, then query by role
Frequent mistakes and how to fix them

A passing Testing Library suite therefore proves behavioral correctness in a model browser, not visual or cross-browser correctness. Mature teams combine it with a small set of end-to-end tests and dedicated accessibility checks such as axe-core.

The short version

Testing Library helps developers check that a piece of a website works the way a visitor would experience it. Instead of looking under the hood, a test looks at the screen like a person does. It finds the button labeled Save, clicks it and checks that a confirmation message appears.

Because tests describe what people see and do, they keep working when the code inside changes. The page only has to behave the same. As a bonus, components that are easy to test this way are usually easier to use with a screen reader too.

Where it makes a difference

A product team maintains a checkout form in a React application with about 40 component tests written against internal state. When the team replaces its form state library, nearly every test fails even though the form still works, and developers spend two days rewriting assertions.

The team rewrites the suite with React Testing Library. Each test now fills fields located with getByLabelText, submits with getByRole('button', { name: 'Place order' }) and waits for the success message with findByText. While writing these queries, developers discover that three inputs lacked proper labels, which they fix.

Six months later, a second refactoring moves the form to a new component structure. The suite passes without changes, the run completes in under ten seconds, and the accessibility fixes found during the rewrite remain covered by tests that fail if a label disappears.