React Testing with Jest and React Testing Library

React Testing Library encourages testing behavior, not implementation. Here’s how to write effective React tests.

Setup

npm install @testing-library/react @testing-library/jest-dom -D

Basic Test

import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';

test('increments counter', () => {
  render(<Counter />);
  
  const button = screen.getByRole('button', { name: /increment/i });
  fireEvent.click(button);
  
  expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

Async Testing

test('loads user data', async () => {
  render(<UserProfile userId={1} />);
  
  expect(screen.getByText(/loading/i)).toBeInTheDocument();
  
  await screen.findByText('John Doe');  // Waits for element
});

Guidelines

  • Query by role, label, or text – not test IDs
  • Test user behavior, not implementation
  • Avoid testing internal state

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.