π§ͺ React Testing Library (RTL)
React Testing Library (RTL) is a lightweight testing library for React. It focuses on testing components from the userβs perspective rather than testing implementation details.
π― 1. Why Use RTL?
- Encourages testing UI behavior, not structure
- Promotes good accessibility by using roles and labels
- Works perfectly with Jest
βοΈ 2. Installation
If you're using Create React App, it's already included. Otherwise:
npm install --save-dev @testing-library/react @testing-library/jest-dom
π§ͺ 3. Basic Example
// Hello.js
export default function Hello() {
return <h1>Hello, World!</h1>;
}
// Hello.test.js
import { render, screen } from '@testing-library/react';
import Hello from './Hello';
test('renders hello message', () => {
render(<Hello />);
expect(screen.getByText('Hello, World!')).toBeInTheDocument();
});
π 4. Common Query Methods
getByText()
β find by visible textgetByRole()
β find by accessibility rolegetByLabelText()
β useful for formsfindBy
β async queries for elements that appear later
π±οΈ 5. Simulating Events
Use fireEvent
or userEvent
to simulate interactions.
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
test('increments counter', () => {
render(<Counter />);
const button = screen.getByText('Increment');
fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
β 6. Best Practices
- Test what the user sees, not internal state or classNames
- Use
screen
for consistency in queries - Write tests that are resilient to UI refactoring
π Summary
- React Testing Library helps you test real user behavior
- Combines well with Jest and DOM matchers
- Encourages accessible, maintainable testing