Next.js Course
Next.js
/
Intermediate

React Testing Library

Definition

A testing utility that allows you to render React components in a virtual DOM and interact with them exactly as a real user would (clicking, typing).

Explain Like I'm New

Jest tests math. React Testing Library (RTL) tests HTML. Instead of looking at the underlying React state, RTL says: 'Render the component. Can I find a button with the text 'Submit'? If I click it, does a success message appear on the screen?'

Real World Example

Writing a test for a `<LoginForm>` component that types an email into the input, clicks the submit button, and asserts that a red error message appears.

Common Use Cases

  • •Component testing
  • •Accessibility testing
  • •Interaction testing

Interactive Example

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

describe('ToggleButton Component', () => {
  it('should toggle text from OFF to ON when clicked', () => {
    
    // 1. Render the component in the virtual DOM
    render(<ToggleButton />);
    
    // 2. Find the button the way a user would (by reading its text!)
    const button = screen.getByRole('button', { name: /off/i });
    expect(button).toBeInTheDocument();

    // 3. Simulate a real user clicking the button
    fireEvent.click(button);

    // 4. Assert the UI updated correctly
    expect(screen.getByRole('button', { name: /on/i })).toBeInTheDocument();
  });
});

Interview Questions

basic

  • What is the primary philosophy of React Testing Library regarding how tests should be written?

intermediate

  • What function from RTL is used to simulate a user clicking a button?

Flash Cards

Question

Primary philosophy?

Click to reveal answer
Answer

'The more your tests resemble the way your software is used, the more confidence they can give you.' RTL forces you to find elements by their accessibility roles or visible text, rather than by class names or component state.

Question

Which function?

Click to reveal answer
Answer

`fireEvent.click()` or the more modern `@testing-library/user-event` package using `userEvent.click()`.