# Testing React

> The three layers of testing in modern React applications: Unit (logic), Component (behavior), and End-to-End (user flows).

Subject: React | Lesson 44 of 48 | 6 min read
Interactive lesson: https://codewithanimation.in/react/testing-react
Previous: [Component-Driven Development](https://codewithanimation.in/react/component-driven-dev.md) | Next: [Rendering Patterns](https://codewithanimation.in/react/rendering-patterns.md)

## The Testing Pyramid

Testing ensures your code works and prevents regressions when you make changes. In React, we generally think about three layers:

**1. Unit Testing:** Testing pure functions in isolation (e.g., `calculateTotal(items)`). Fast and cheap. Usually done with **Vitest** or Jest.

**2. Component Testing:** Testing a single React component (e.g., `<CheckoutForm />`). We test how it behaves, not how it's written. Usually done with **React Testing Library**.

**3. End-to-End (E2E) Testing:** Spinning up a real browser and clicking through the app like a real user (e.g., adding an item to cart and checking out). Slow but highly confident. Done with **Playwright** or Cypress.

## Testing Behavior, Not Implementation

Historically, developers tested React components by checking their internal state (e.g., `expect(wrapper.state('isOpen')).toBe(true)`).

This was fragile. If you refactored the component to use `useReducer` instead of `useState`, the test would break even if the UI worked perfectly.

**React Testing Library (RTL)** changed the paradigm. It forces you to test what the user sees: `expect(screen.getByText('Hello')).toBeInTheDocument()`.

## Writing an RTL Test

A typical component test follows the AAA pattern: Arrange, Act, Assert.

**Arrange:** `render(<LoginForm />)`

**Act:** `fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'test@test.com' } })`

**Assert:** `expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled()`

## Common mistake: The Mucking of Mocks

The hardest part of component testing is dealing with dependencies. If your `<UserProfile />` fetches data on mount, running `render(<UserProfile />)` in a test will crash because there is no API.

You have to mock the fetch request. Tools like **MSW (Mock Service Worker)** are the modern standard for intercepting these requests at the network level, keeping your component code clean.

## Tip: Don't test everything

Chasing 100% test coverage is usually a waste of time. Focus your component tests on complex, interactive UI (like forms or data tables).

Leave simple styling or layout checks to visual regression tools or manual QA. Focus your E2E tests on your most critical business flows (like the checkout process).

## Try it: The Automated Test Runner

Watch a simulated React Testing Library test run. The test runner executes the code on the left line-by-line, which automatically interacts with the rendered component on the right, verifying its behavior without a human.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/testing-react

## Check yourself

### Question 1

What is the core philosophy of React Testing Library (RTL)?

- A. To test the internal `useState` variables to ensure they update correctly.
- B. To interact with the component exactly how a real user would, testing the DOM output rather than the implementation details.
- C. To take screenshots of the component and compare them pixel-by-pixel.

Correct answer: B

RTL's guiding principle is: 'The more your tests resemble the way your software is used, the more confidence they can give you.' Users don't know about `useState`; they just know they clicked a button and text appeared.

### Question 2

Which type of test provides the highest confidence that the entire application works, but is the slowest to run?

- A. Unit Tests (Vitest/Jest)
- B. Component Tests (React Testing Library)
- C. End-to-End Tests (Playwright/Cypress)

Correct answer: C

E2E tests spin up an actual Chromium browser, navigate to a URL, and interact with the live app (including the real backend database). They are slow and sometimes flaky, but catch errors that unit tests miss.

### Question 3

What is MSW (Mock Service Worker) primarily used for in React testing?

- A. To intercept network requests and return mock data, preventing components from hitting real APIs during tests.
- B. To mock the CSS layout engine so components render faster.
- C. To act as a fake Redux store.

Correct answer: A

MSW intercepts requests at the network level using Service Workers. Your component still calls `fetch('/api/user')`, but MSW catches it and returns your predefined mock JSON, making testing data-fetching components trivial.

## Remember this

- Unit Tests (Vitest) are for pure functions.
- Component Tests (RTL) are for isolated UI behavior.
- E2E Tests (Playwright) are for full user flows in a real browser.
- React Testing Library forces you to test the DOM (what the user sees), not the implementation (how it's coded).
- Use MSW to cleanly mock API requests during component tests.
