React Testing Library Guide

React Testing LibraryTest Like a User

Simple and complete testing utilities for React. Test components the way users interact with them.

Contents

React Testing Library Basics

React Testing Library focuses on testing components from the user's perspective. It encourages accessible queries.

bash
# Installation
npm install --save-dev @testing-library/react @testing-library/jest-dom
javascript
// Basic Test
import { render, screen } from '@testing-library/react';
import Button from './Button';

test('renders button', () => {
  render(<Button>Click me</Button>);
  const button = screen.getByRole('button', { name: /click me/i });
  expect(button).toBeInTheDocument();
});

// Component Test
import { render, screen } from '@testing-library/react';
import UserProfile from './UserProfile';

test('displays user name', () => {
  const user = { name: 'John Doe', email: 'john@example.com' };
  render(<UserProfile user={user} />);
  expect(screen.getByText('John Doe')).toBeInTheDocument();
});