What is @testing-library/react?
The @testing-library/react package is a set of utilities that allow you to work with React components in a way that simulates user interaction as closely as possible. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices. Its primary aim is to test the component the way users would. Therefore, it avoids including details about the component's internal structure, such as state or lifecycle methods, and instead focuses on making tests easy to write and understand.
What are @testing-library/react's main functionalities?
Rendering Components
This feature allows you to render a React component into a container which is appended to document.body. It provides utility functions to interact with the rendered component.
import { render } from '@testing-library/react';
const { getByText } = render(<button>Click me</button>);
expect(getByText(/click me/i)).toBeInTheDocument();
Querying Elements
Provides various methods to query elements from the rendered component, such as getByText, getByRole, etc., making it easier to assert their presence and properties.
import { screen } from '@testing-library/react';
render(<div>Hello World</div>);
expect(screen.getByText('Hello World')).toBeInTheDocument();
User Events Simulation
Enables the simulation of user actions like clicking, typing, etc., on the rendered components. This is crucial for testing interactive elements.
import { render, fireEvent } from '@testing-library/react';
const { getByLabelText, getByText } = render(<label htmlFor='checkbox'>Check this box</label>
<input id='checkbox' type='checkbox' />);
fireEvent.click(getByText('Check this box'));
expect(getByLabelText('Check this box')).toBeChecked();
Other packages similar to @testing-library/react
enzyme
Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components' output. It allows you to manipulate, traverse, and in some ways simulate runtime given the output. Enzyme's API is meant to be intuitive and flexible by mimicking jQuery's API for DOM manipulation and traversal. Compared to @testing-library/react, Enzyme provides more direct access to the component's internal structure, which can be both a strength and a weakness depending on the testing philosophy.
cypress
Cypress is a front-end testing tool built for the modern web. It is not limited to React alone but can test any web application. Its testing approach is somewhat different from @testing-library/react as it runs in a real browser and performs end-to-end testing. While @testing-library/react focuses on unit and integration tests from a user's perspective, Cypress provides a more comprehensive testing solution including full end-to-end testing capabilities.