The @testing-library/react is a comprehensive set of testing utilities for React that encourages good testing practices. It provides light utility functions on top of react-dom
and react-dom/test-utils
, promoting better testing practices. This library is focused on making your tests resemble the way your software is used, supporting both React Hooks and Classes.
To use @testing-library/react, you first need to install it as a devDependency in your project using npm or yarn. Installation can be done with the following shell commands:
npm install --save-dev @testing-library/react
yarn add --dev @testing-library/react
In a simple use case, here is how to use it:
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders learn react link', () => {
render(<MyComponent />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
This testing pattern uses tools from the library to render a React component, query the rendered output, and make assertions based on the queried output.
For complex usage and more examples, refer to the documentation or the project's GitHub repository.
The official @testing-library/react documentation can be found here. The docs give you an in-depth understanding of how to use the library, different utilities it provides, and examples of how to use them. You can also find various useful examples of testing different libraries in react-testing-library-examples
codesandbox.