What is React Testing Library (RTL)?
React Testing Library (RTL) is a lightweight testing library designed to test React components in a way that mirrors how users interact with them.
Main principles of RTL:
- Focuses on what the user sees and does, not on the implementation details of components.
- Encourages tests that are resilient to internal changes but sensitive to real user behavior.
- Avoids using component internals like
state
orprops
directly in tests.
Key features:
- Queries like
getByText
,getByRole
, andgetByLabelText
help you find elements the same way a user would. - Simulates real user events like clicks, typing, or form submissions using
@testing-library/user-event
. - Works seamlessly with Jest for a complete testing setup.
Example:
import { render, screen, fireEvent } from '@testing-library/react'; import Button from './Button'; test('calls onClick when clicked', () => { const handleClick = jest.fn(); render(<Button onClick={handleClick} />); fireEvent.click(screen.getByRole('button')); expect(handleClick).toHaveBeenCalledTimes(1); });
React Testing Library helps ensure your tests are user-focused, leading to better and more maintainable code.