React Testing with Jest and React Testing Library

On this page

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

Setup

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

Basic Test

JSX11 lines
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

JSX7 lines
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.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

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.