Testing React components in Jest requires combining testing tools with rendering methods:
Common Testing Tools:
- @testing-library/react: Officially recommended React testing library
- react-test-renderer: For snapshot testing
- enzyme: Traditional React component testing tool (less commonly used)
Basic Testing Example:
javascriptimport { render, screen, fireEvent } from '@testing-library/react'; import Button from './Button'; test('renders button with text', () => { render(<Button>Click me</Button>); expect(screen.getByText('Click me')).toBeInTheDocument(); }); test('calls onClick when clicked', () => { const handleClick = jest.fn(); render(<Button onClick={handleClick}>Click me</Button>); fireEvent.click(screen.getByText('Click me')); expect(handleClick).toHaveBeenCalledTimes(1); });
Common Query Methods:
getByText(): Find elements by textgetByRole(): Find elements by rolegetByTestId(): Find by data-testid attributequeryByText(): Find element, returns null if not foundfindByText(): Async find element
Testing Async Components:
javascripttest('loads and displays data', async () => { render(<UserList />); expect(screen.getByText('Loading...')).toBeInTheDocument(); await waitFor(() => { expect(screen.getByText('John')).toBeInTheDocument(); }); });
Best Practices:
- Test user behavior, not implementation details
- Use
@testing-library/reactinstead of enzyme - Use
data-testidas a last resort - Avoid testing internal state, test visible output
- Keep tests simple and readable