Testing React Apps
Unit testing with Jest, component testing with React Testing Library, and E2E testing.
Overview
Testing ensures reliability and prevents regressions in React applications.
Key Concepts
- Jest — Test runner with assertion library
- React Testing Library — Test components as users interact with them
- Unit Tests — Test individual functions and components
- Integration Tests — Test component interactions
- E2E Tests — Test complete user flows with Cypress or Playwright
Code Examples
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Counter from './Counter';
describe('Counter', () => {
it('increments count when button clicked', () => {
render(<Counter />);
const button = screen.getByRole('button', { name: /increment/i });
fireEvent.click(button);
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();
});
it('resets count when reset clicked', async () => {
render(<Counter />);
const user = userEvent.setup();
await user.click(screen.getByText(/increment/i));
await user.click(screen.getByText(/increment/i));
await user.click(screen.getByText(/reset/i));
expect(screen.getByText(/count: 0/i)).toBeInTheDocument();
});
});
// Async testing
describe('UserProfile', () => {
it('displays user data after loading', async () => {
render(<UserProfile userId={1} />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText('John Doe')).toBeInTheDocument();
});
});
});
Practice
Write tests for a login form including validation, submission, and error states.