乐闻世界logo
搜索文章和话题

How to test React components in Jest? What are the common testing tools and query methods?

2月19日 19:53

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:

javascript
import { 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 text
  • getByRole(): Find elements by role
  • getByTestId(): Find by data-testid attribute
  • queryByText(): Find element, returns null if not found
  • findByText(): Async find element

Testing Async Components:

javascript
test('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/react instead of enzyme
  • Use data-testid as a last resort
  • Avoid testing internal state, test visible output
  • Keep tests simple and readable
标签:Jest