SmartCodingTips

πŸ§ͺ React Testing Library (RTL)

React Testing Library (RTL) is a lightweight testing library for React. It focuses on testing components from the user’s perspective rather than testing implementation details.


🎯 1. Why Use RTL?

  • Encourages testing UI behavior, not structure
  • Promotes good accessibility by using roles and labels
  • Works perfectly with Jest

βš™οΈ 2. Installation

If you're using Create React App, it's already included. Otherwise:


npm install --save-dev @testing-library/react @testing-library/jest-dom

πŸ§ͺ 3. Basic Example


// Hello.js
export default function Hello() {
  return <h1>Hello, World!</h1>;
}

// Hello.test.js
import { render, screen } from '@testing-library/react';
import Hello from './Hello';

test('renders hello message', () => {
  render(<Hello />);
  expect(screen.getByText('Hello, World!')).toBeInTheDocument();
});

πŸ” 4. Common Query Methods

  • getByText() – find by visible text
  • getByRole() – find by accessibility role
  • getByLabelText() – useful for forms
  • findBy – async queries for elements that appear later

πŸ–±οΈ 5. Simulating Events

Use fireEvent or userEvent to simulate interactions.


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

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

βœ… 6. Best Practices

  • Test what the user sees, not internal state or classNames
  • Use screen for consistency in queries
  • Write tests that are resilient to UI refactoring

πŸ“‹ Summary

  • React Testing Library helps you test real user behavior
  • Combines well with Jest and DOM matchers
  • Encourages accessible, maintainable testing