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()
})
test("...", async () => { ... })is one test: its name describes the behaviour being checked, its body holds the steps.render(<Counter />)renders the component into a pretend DOM (jsdom) inside the test, without opening a browser.screenis the whole rendered page.screen.getByText("Count: 0")finds the element whose text is exactlyCount: 0.userEvent.setup()and thenawait user.click(...)imitate a real user's click, step by step: the pointer (mouse) events, the focus, then the click. The click is async (it has to be waited for), soawaitis required.expect(...).toBeInTheDocument()is called an assertion (a statement that gets checked): this assertion makes sure the element is on the page. If it isn't,expectthrows an error, and the test fails.
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:
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 itsaria-labelif it has one).getByLabelText("Email"): an input by its label.getByPlaceholderText("Search..."): an input by its placeholder.getByText("Count: 0"): an ordinary element by its text.getByDisplayValue,getByAltText(images),getByTitle.getByTestId("add"): by thedata-testidattribute. 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:
getBy...throws an error if the element isn't there.queryBy...returnsnullif the element isn't there. SoqueryByis used for checking something that must not be there:expect(screen.queryByText("Failed")).not.toBeInTheDocument().findBy...waits for an element that appears later, for example after a fetch:await screen.findByText("Budi"). By default,findBywaits up to 1 second.
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
expect(actual)returns an object holding methods called matchers, heretoBe. Each matcher still remembersactual, because the matcher was made insideexpect. That's a closure, which you learned on the JavaScript track.- Real matchers throw an error when they fail, and the test runner catches that error and marks the test as failed.
- In the exercise, you build a mini version called
makeAssertion(text). To keep it easy to check, its methods returntrueorfalseinstead of throwing. For example,makeAssertion("hello world").toContain("world")givestrue, andmakeAssertion("").toBeInTheDocument()givesfalse.
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
- Forgetting
awaitonuser.click. The assertion runs before the click is done, soCount: 1isn't there yet and the test fails. getByTestIdeverywhere. The test still passes when the button turns into adivthat can't be used from the keyboard. Start withgetByRole.- Testing the state inside. Checking the value of
countinside the component, or how many times it renders, makes tests fail when the code is made neater, even though the screen looks the same. Check what the user sees. getByfor something that must not be there.getByalready throws an error beforeexpectcan check anything. UsequeryBy.- Forgetting
globals: true. Without it, the page is not cleaned between tests. So a second test in the same file that rendersCounterfails withFound multiple elements with the role "button" and name "Add". Addglobals: true, or writeafterEach(cleanup)insrc/setupTests.js(afterEachfromvitest,cleanupfrom@testing-library/react).
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.