Repo of the Day
testing-library/react-testing-library
Published: Dec 20, 2021
Open repository ↗React testing library - great testing library to compliment apps
Summary
React Testing Library is a lightweight set of utilities built on top of react-dom and react-dom/test-utils for testing React components. Its stated principle is that tests should resemble how software is actually used, so the API works through DOM nodes rather than component instances. This keeps test assertions focused on user-visible behavior instead of internal implementation details.
What it is useful for
It is useful for writing maintainable React component tests that survive refactors of internal implementation. The README frames the problem as wanting tests that "avoid including implementation details" so reworking a component does not break unrelated tests. It works with both function and class components, including components built with React Hooks, and pairs naturally with @testing-library/jest-dom for matchers like toBeInTheDocument and toHaveTextContent, though jest-dom is not required.
It is also useful for asynchronous flows: queries like findByRole return promises, letting tests wait for elements that appear after a fetch resolves, mirroring how a manual tester would watch the page.
How engineers can use it
Install as a dev dependency:
npm install --save-dev @testing-library/react @testing-library/dom
Or with yarn: yarn add --dev @testing-library/react @testing-library/dom. Versions 13+ require React 18; for older React, install @testing-library/react@12. A documented quirk: React DOM 16.8 emits an act(...) warning during tests, and the README provides a snippet to filter console.error if you cannot upgrade to 16.9.
A typical test calls render(<Component />), then uses screen queries such as getByLabelText, queryByText, and findByRole to locate nodes, and fireEvent.click or fireEvent.change to drive interactions. The README's basic example renders a HiddenMessage component, asserts the message is hidden with queryByText, clicks the checkbox via getByLabelText(/show/i), and then asserts the message is in the document.
For network-driven UI, the README's complex example combines the library with Mock Service Worker. It renders a Login form, fills in username and password, clicks submit, and uses await screen.findByRole('alert') to wait for the success message before asserting the token was stored. A second test overrides the MSW handler to return a 500 and asserts the error alert appears instead.
For custom hooks, the README points to React Hooks Testing Library but cautions that single-use hooks are better tested through the component that uses them. Full documentation lives at testing-library.com/react.