What You’ll Learn in This Tutorial
✓ Setup
✓ Writing basic tests
✓ Query selection
✓ User events
✓ Async testing
Step 1: Setup
npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event jest jest-environment-jsdom
Step 2: Basic Tests
// Button.tsx
export function Button({ onClick, children }) {
return <button onClick={onClick}>{children}</button>;
}
// Button.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Button } from './Button';
describe('Button', () => {
it('renders correctly', () => {
render(<Button>Click me</Button>);
expect(screen.getByRole('button', { name: 'Click me' })).toBeInTheDocument();
});
it('calls onClick when clicked', async () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick}>Click me</Button>);
await userEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
});
Step 3: Query Selection
// Priority order (accessibility-focused)
screen.getByRole('button', { name: 'Submit' }); // Highest priority
screen.getByLabelText('Email'); // Form elements
screen.getByPlaceholderText('Enter email'); // Placeholder
screen.getByText('Hello World'); // Text
screen.getByTestId('custom-element'); // Last resort
// Existence checks
screen.queryByRole('button'); // Returns null if not found
await screen.findByRole('button'); // Waits asynchronously
Step 4: Form Testing
// LoginForm.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
it('submits form with correct values', async () => {
const handleSubmit = jest.fn();
render(<LoginForm onSubmit={handleSubmit} />);
await userEvent.type(screen.getByLabelText('Email'), 'test@example.com');
await userEvent.type(screen.getByLabelText('Password'), 'password123');
await userEvent.click(screen.getByRole('button', { name: 'Login' }));
expect(handleSubmit).toHaveBeenCalledWith({
email: 'test@example.com',
password: 'password123'
});
});
Step 5: Async Testing
// UserList.test.tsx
import { render, screen, waitFor } from '@testing-library/react';
import { UserList } from './UserList';
it('displays users after loading', async () => {
render(<UserList />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText('Alice')).toBeInTheDocument();
});
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
});
Step 6: Mocking
// API mock
jest.mock('./api', () => ({
fetchUsers: jest.fn().mockResolvedValue([
{ id: 1, name: 'Alice' }
])
}));
// Component mock
jest.mock('./Header', () => ({
Header: () => <div data-testid="mock-header">Header</div>
}));
Summary
React Testing Library encourages writing tests from the user’s perspective. Test using accessibility-conscious queries.
← Back to list