Learn Testing React

A test is code that uses a component like a user would, then checks the result. The basic pattern: render(<Component />), find elements through screen (the…

You make a component's code neater, everything looks fine, then a week later someone reports that the Add button stopped working. Clicking every button by hand each time the code changes is tiring. Tests do it for you.

A test is a small piece of code that uses your component the way a user would, then checks the result. Tests run automatically, every time the code changes. In React, two tools are most often used together. Vitest is the test runner: the program that runs the tests and reports pass or fail. React Testing Library (RTL) renders components and finds elements in them. A test works like the quality checker at a bread factory. The checker doesn't care how the machines inside the factory work. The checker takes a loaf, checks its shape, squeezes it, tastes it, then says pass or fail. Here the loaf is your component, the machines are the code and state inside the component, and the quality checker is the test. Testing Library works the same way: it doesn't read the state inside a component, it checks what the user can see and do.

A first test: render, act, check

This is the component being tested:

// Counter.jsx
import { useState } from "react"

export default function Counter() {
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Add</button>
    </div>
  )
}

This is its test, in a separate file:

// Counter.test.jsx
import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { test, expect } from "vitest"
import Counter from "./Counter"

test("count goes up when the Add button is clicked", async () => {
  const user = userEvent.setup()
  render(<Counter />)

  expect(screen.getByText("Count: 0")).toBeInTheDocument()

  await user.click(screen.getByRole("button", { name: "Add" }))

  expect(screen.getByText("Count: 1")).toBeInTheDocument()
})

Run it with npx vitest run. When it passes, the terminal shows:

 ✓ src/Counter.test.jsx (1 test) 48ms

 Test Files  1 passed (1)
      Tests  1 passed (1)

If the button is broken and the number doesn't go up, getByText("Count: 1") finds nothing and throws:

 FAIL  src/Counter.test.jsx > count goes up when the Add button is clicked
TestingLibraryElementError: Unable to find an element with the text: Count: 1. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

Find elements the way a user does

A function that finds elements is called a query. Testing Library has a recommended order of queries, starting from the one closest to how a user (and a screen reader, a program that reads the page aloud) finds an element:

  1. getByRole("button", { name: "Add" }): by role, meaning the element's part on the page (button, heading, textbox, checkbox), and its name (what a screen reader reads out: the button's text, or its aria-label if it has one).
  2. getByLabelText("Email"): an input by its label.
  3. getByPlaceholderText("Search..."): an input by its placeholder.
  4. getByText("Count: 0"): an ordinary element by its text.
  5. getByDisplayValue, getByAltText (images), getByTitle.
  6. getByTestId("add"): by the data-testid attribute. The last choice, because users never see it.

So the recommended query is getByRole. The difference between these queries shows when the Add button is changed. Say all three versions of the button (the original and the two in the table) keep data-testid="add":

The button changed into getByRole getByText("Add") getByTestId
<button aria-label="Add">+</button> (an icon) passes fails passes
<div onClick={...}>Add</div> fails passes passes

The icon version is still the same button to a user, and only getByText wrongly treats it as broken. The div version really is broken: it can't be pressed from the keyboard, and a screen reader doesn't know it's a button. Only getByRole catches that problem.

The start of a query's name has a meaning too:

Behind expect

expect itself isn't magic. Here's a small version of expect written by hand:

function expect(actual) {
  return {
    toBe(expected) {
      if (actual !== expected) {
        throw new Error(`Expected ${expected}, received ${actual}`)
      }
    },
  }
}

expect(1 + 1).toBe(2) // stays quiet: passes
expect(1 + 1).toBe(3) // throws an error: the test fails

Installing the tools

Install all the tools from the terminal (-D records them as tools for development):

npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom

Then in vite.config.js, add test: { globals: true, environment: "jsdom", setupFiles: "./src/setupTests.js" }. Fill src/setupTests.js with one line: import "@testing-library/jest-dom/vitest". That line is what adds matchers such as toBeInTheDocument. globals: true lets Testing Library clean the page after each test.

⚠️ Tests that pass when things are broken, or fail when they're fine

TL;DR: A test is code that uses a component like a user would, then checks the result. The basic pattern: render(<Component />), find elements through screen (the rendered page), act with await user.click(...), then check with an assertion (a statement that gets checked) such as expect(...).toBeInTheDocument(). Vitest runs the tests, and React Testing Library renders components and finds elements. The query order (queries are functions that find elements): getByRole first, then getByLabelText, getByPlaceholderText, getByText, and getByTestId last. queryBy for what must not be there, findBy for what appears later. expect(x) returns an object of matchers (checking methods) that remember x and throw an error when a check fails.

⚡ Render, act, check

Write:

test("count goes up when the Add button is clicked", async () => {
  const user = userEvent.setup()
  render(<Counter />)

  expect(screen.getByText("Count: 0")).toBeInTheDocument()

  await user.click(screen.getByRole("button", { name: "Add" }))

  expect(screen.getByText("Count: 1")).toBeInTheDocument()
})

Meaning: A test is code that uses a component like a user would, then checks the result. This test renders Counter, a component that shows Count: 0 and an Add button. screen.getByRole("button", { name: "Add" }) finds the Add button, and await user.click(...) clicks it. expect(...).toBeInTheDocument() makes sure the text is on the page. If the button breaks, getByText("Count: 1") finds nothing and the test fails.

⚡ Find elements the way users do

Guess first: the Add button is changed into an icon, <button aria-label="Add">+</button>. The visible text is only +, and aria-label gives the button the name Add. Does getByText("Add") still pass?

It fails, even though for the user it's still the same button: getByText looks for the visible text, which is +. getByRole("button", { name: "Add" }) still passes.

Meaning: Choose getByRole first: this query (a function that finds elements) finds an element by its role (its part on the page, such as button) and its name, the way users and screen readers (programs that read the page aloud) do. getByTestId, which finds an element by its data-testid attribute, is the last choice, because users never see it.

⚡ Behind expect

Write:

expect(1 + 1).toBe(2) // stays quiet: passes
expect(1 + 1).toBe(3) // throws an error: the test fails

Meaning: toBe is a matcher, a method from expect that compares values. If they match, the matcher does nothing and the test passes. If they don't, the matcher throws an error, then the test runner (the program that runs the tests, such as Vitest) catches that error and marks the test as failed.

What you will learn