React Testing Library encourages testing behavior, not implementation. Here’s how to write effective React tests.
Setup
npm install @testing-library/react @testing-library/jest-dom -DBasic Test
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
test('increments counter', () => {
render(<Counter />);
const button = screen.getByRole('button', { name: /increment/i });
fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});Async Testing
test('loads user data', async () => {
render(<UserProfile userId={1} />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
await screen.findByText('John Doe'); // Waits for element
});Guidelines
- Query by role, label, or text – not test IDs
- Test user behavior, not implementation
- Avoid testing internal state
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.