Skip to content

React Component Testing with Testing Library

Medium ~50 min

What you'll build

A small React app with a counter component and a todo list component, tested with React Testing Library using user-centric queries and interactions.

Goals

  • Set up React Testing Library with Jest
  • Test component rendering with getByRole and getByText
  • Test user interactions with userEvent
  • Test async component behavior
  • Follow the Testing Library philosophy of testing like a user

Prerequisites

  • Basic React knowledge (components, state, events)
  • Completed Project 1 or equivalent Jest experience
  • Node.js and npm installed

Steps

  1. 1

    Set up the React testing environment

    Install dependencies: npm install --save-dev @testing-library/react @testing-library/jest-dom @testing-library/user-event.

    Code
    // jest.setup.js
    import '@testing-library/jest-dom';

    Expected result

    Testing Library packages are installed.

  2. 2

    Create a Counter component

    Create a simple counter component with increment and decrement buttons.

    Code
    function Counter() {
      const [count, setCount] = React.useState(0);
      return (
        <div>
          <span role="display">{count}</span>
          <button onClick={() => setCount(c => c + 1)}>Increment</button>
          <button onClick={() => setCount(c => c - 1)}>Decrement</button>
        </div>
      );
    }

    Expected result

    Counter component is created.

  3. 3

    Test the Counter component

    Write tests that interact with the component like a real user would — click buttons and check the display.

    Code
    import { render, screen } from '@testing-library/react';
    import userEvent from '@testing-library/user-event';
    import Counter from './Counter';
    
    test('increments counter', async () => {
      render(<Counter />);
      expect(screen.getByRole('display')).toHaveTextContent('0');
      await userEvent.click(screen.getByText('Increment'));
      expect(screen.getByRole('display')).toHaveTextContent('1');
    });

    Expected result

    Counter test passes.

  4. 4

    Create and test a Todo component

    Create a TodoList component that adds items. Test adding an item through the input and button.

    Code
    test('adds a todo item', async () => {
      render(<TodoList />);
      const input = screen.getByRole('textbox');
      const button = screen.getByText('Add');
      await userEvent.type(input, 'Buy milk');
      await userEvent.click(button);
      expect(screen.getByText('Buy milk')).toBeInTheDocument();
    });

    Expected result

    Todo test passes — item appears after adding.

  5. 5

    Add boundary test cases

    Add boundary-value cases to the test suite: empty array, zero, maximum value, null/undefined. Boundaries are where bugs most often hide, so they must be explicitly covered.

    Code
    describe("boundary cases", () => {
      it("handles empty array", () => {
        expect(func([])).toEqual([]);
      });
    
      it("handles zero", () => {
        expect(func(0)).toBe(0);
      });
    
      it("handles null", () => {
        expect(() => func(null)).toThrow();
      });
    
      it("handles max value", () => {
        expect(func(Number.MAX_SAFE_INTEGER)).toBeDefined();
      });
    });

    Expected result

    All boundary cases pass with no uncaught exceptions.

Try it yourself

What you learned

You learned to test React components the way users interact with them: querying by role and text, using userEvent for realistic interactions, and asserting on visible output. This approach creates robust tests that survive refactoring.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic