Testing Library
UI testing utilities that query rendered output the way users perceive it, by role, label, and text.
Official Documentation ↗DOM Testing Library v10. Check the official docs for the latest API surface.Installation
npm install -D @testing-library/dom @testing-library/reactpnpm add -D @testing-library/reactMethods
No methods match this filter.
UI testing utilities that query rendered output the way users perceive it, by role, label, and text.
Overview
Testing Library renders components and lets tests interrogate them like users do: by role, label, and visible text rather than implementation details. Queries come in get, query, and find variants for assertive, negative, and async cases.
user-event drives realistic interaction sequences, waitFor handles asynchronous settling, and within scopes queries to subtrees. The guiding rule, tests that resemble how software is used, keeps suites resilient to refactors.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
render— Mounts the component into a detached container and exposes queries and helpers.screen queries— Queries the document by accessibility semantics first, with text as a last resort.fireEvent / userEvent— Dispatches events directly, or drives realistic interaction sequences via user-event.waitFor / findBy— Waits for async updates, with findBy* combining query and wait in one call.
Usage Notes
- Write queries against accessible names first; add semantics to components when queries need them.
- Prefer findBy over waitFor plus getBy for one-step async assertions.
- Model user flows, typing and clicking, rather than calling handlers directly.
Common Pitfalls
- Testing className or internal state couples suites to implementation and breaks on refactor.
- Empty-string assertions on container.innerHTML verify nothing meaningful.
- Forgetting userEvent.setup with the modern API leaves interactions silently inert.
FAQ
- Why do queries prefer roles over test IDs?
- Roles, labels, and accessible names mirror how assistive technology sees the page. Tests written against them fail when accessibility breaks, which is exactly the regression you want caught, while data-testid survives broken semantics.
- fireEvent or user-event, which should I use?
- user-event simulates realistic browser behavior, focus, keyboard state, pointer events, so it catches interaction bugs fireEvent misses. Reserve fireEvent for edge dispatches where you need exact control of the event.
- What causes "not wrapped in act" warnings?
- State updates happening after the test finished synchronously, usually from unresolved promises. Prefer findBy* and waitFor over manual sleeps, and ensure fake timers advance; the warning disappears when updates settle inside awaited helpers.
Report a problem with this API docOpens a pre-filled issue on GitHub.