AI summary
What JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed., React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role., jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser. and PlaywrightA tool from Microsoft that opens a real browser, such as Chrome or Firefox, and clicks through your app the way a user would. each do when you test React components, and what the act()A function from React that finishes all pending renders and state updates before the test checks the screen. warning actually means.
- JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. runs the tests, React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role. renders and queries components, and jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser. imitates the browser.
- Wait for async data with a findByA family of React Testing Library queries, such as findByRole, that keep looking for an element until it appears or the time runs out. query, which retries until the element appears, and look elements up by their role, like button or heading, first.
- act()A function from React that finishes all pending renders and state updates before the test checks the screen. belongs to React, and React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role. usually calls it for you.
The first thing that gets confusing with React tests is where one tool stops and the next one starts.
JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. runs the tests, React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role. renders your components and looks things up in them, and jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser. imitates the browser so all of that works inside Node, which runs JavaScript outside the browser. It gives your components a DOM to render into: the tree of elements a browser normally builds from the page.
Anything that needs real layout or navigation needs an end-to-end tool like PlaywrightA tool from Microsoft that opens a real browser, such as Chrome or Firefox, and clicks through your app the way a user would., which drives a real browser through your whole app. Cypress and Puppeteer are two other tools that do the same job.
There are three levels of test. A function test calls plain code, with no browser at all. A component test renders a component tree in jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser. and checks the output. An end-to-end test runs the whole app in a real browser.
What to install
Since React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role. 16, @testing-library/dom is a separate peer dependencyA package a library needs but doesn't install for you. You add it to your own project, and the library uses that copy., so you install it yourself next to the library. The library itself needs React 18 or 19.
JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed.’s default environment is node, which has no DOM. For jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser., install jest-environment-jsdom and select it with JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed.’s testEnvironment option. In a ViteA build tool and dev server for frontend projects. Many new React projects start with it. project, the vitest package can do the same job as JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed..
The test below uses two more packages. @testing-library/user-event simulates a user’s clicks and typing. expect is the function a test uses to check a value. @testing-library/jest-dom adds checks like toHaveTextContent and toBeDisabled to it.
JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. also can’t read JSX or import lines on its own. Babel translates your test files into plain JavaScript before JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. runs them, which takes three more packages and a config file.
In a project that already has react and react-dom, the full install is:
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-event @babel/core @babel/preset-env @babel/preset-reactThen two small config files, one for Babel and one that picks jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser. for JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed.:
// babel.config.js
module.exports = {
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-react"],
};// jest.config.js
module.exports = { testEnvironment: "jsdom" };A simple Jest test
JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. runs the test. The test calls sum, expect(value) takes the result, and toBe compares it with the value you expected. Nothing here needs React.
// sum.test.js
const sum = require("./sum");
test("adds 1 + 2 to equal 3", () => {
expect(sum(1, 2)).toBe(3);
});A component test with React Testing Library
Say the Fetch component loads data from an API when you press its button, puts it in a heading and disables the button. The component itself isn’t shown here. The test also assumes the test setup replaces the /greeting request with a mockA fake stand-in for something real, such as a server, that a test controls and that returns the answer the test expects. that returns “hello there”, because in jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser. there’s no real server behind it:
// fetch.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import Fetch from "./fetch";
test("loads and displays greeting", async () => {
const user = userEvent.setup();
render(<Fetch url="/greeting" />);
await user.click(screen.getByRole("button", { name: "Load Greeting" }));
// findBy* retries until the element shows up or the timeout passes.
const heading = await screen.findByRole("heading");
expect(heading).toHaveTextContent("hello there");
expect(screen.getByRole("button")).toBeDisabled();
});The line that waits for the data is findByRole. It retries until it finds the element or the default 1000 ms runs out. getBy answers immediately and throws if it finds nothing.
user.click has its own await only because it returns a promise. It doesn’t wait for the API response; findByRole does that. When I first wrote this article, in Turkish in 2022, I used await userEvent.click and wrote that it waited for the API request. That was wrong.
userEvent.setup() gives you one simulated user whose clicks and key presses share state, like a key that is still held down. The user-event docs recommend calling it before rendering, as the test does.
For queries, reach for getByRole first. An element’s role is what it’s for, like button or heading. A screen reader announces the element by that role. The React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role. docs put role queries first in their recommended order, because they’re closest to what users and screen readers see.
Since jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser. doesn’t do layout, you can’t verify size or scroll behavior here. Something like drag to scroll needs a test in a real browser.
What act() does
act() belongs to React, not React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role.. It batches render and state updates and finishes them before expect runs.
React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role.’s render and user-event calls already wrap their work in act() for you. The library also sets IS_REACT_ACT_ENVIRONMENT, the global flag that tells React it’s running in a test.
React prints a “not wrapped in act” warning when a state update happens outside act(). It means your test may be checking the screen before that update finishes.
A timer is a common cause. The countdown in my Moment.js countdown article updates its state every second from setInterval, outside anything the test does.
Take a countdown like that one, and say it starts at 5 and drops by one every second. A test that waits a bit over a second with a plain setTimeout, say 1100 ms, and then checks the number passes, but JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. still prints this first:
console.error
An update to Countdown inside a test was not wrapped in act(...).When you see it, don’t start by adding act by hand. Check whether the test actually waits for the update. Usually what’s missing is a findBy, or a waitFor, which reruns a check until it passes.
In the countdown, the number changes every 1000 ms, which is the same as the findBy default timeout. So give the wait a longer timeout, or it gives up right before the number changes:
test("shows 4 after a second", async () => {
render(<Countdown />);
expect(await screen.findByText("4", {}, { timeout: 1500 })).toBeInTheDocument();
});This test passes without the warning:
PASS ./countdown.test.jsx
✓ shows 4 after a second (1015 ms)If you’re testing React directly without a library, import act from the react package. The old one in react-dom/test-utils is deprecated.
Without the library you also set IS_REACT_ACT_ENVIRONMENT yourself, and you render with createRoot, since ReactDOM.render is gone in React 19. In the example, App is any component that shows 1.
The React docs recommend the await act(async () => ...) form. The example uses it, which is JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed.’s other name for test:
// act.test.jsx
import { act } from "react";
import { createRoot } from "react-dom/client";
import App from "./app";
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
it("renders 1", async () => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
root.render(<App />);
});
expect(container.textContent).toBe("1");
await act(async () => root.unmount());
container.remove();
});With a small Fetch component and a fetch mockA fake stand-in for something real, such as a server, that a test controls and that returns the answer the test expects. added, the other three tests in this article (sum, Fetch and act) pass on JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. 30, React 19 and React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role. 16:
PASS ./act.test.jsx
PASS ./sum.test.js
PASS ./fetch.test.jsx (11.101 s)
Test Suites: 3 passed, 3 total
Tests: 3 passed, 3 totalWhich kind of test to write
- A plain function: JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. on its own.
- A component’s output and interactions: JestA JavaScript test runner. It finds your test files, runs each test and reports which ones passed. and React Testing LibraryA library that renders React components inside a test and finds elements in the result the way a user would, by their text or role. on jsdomA JavaScript library that imitates the browser’s page structure so tests can create and click elements without opening a browser..
- Layout, scrolling or a critical flow like payments or signup: a real browser, with PlaywrightA tool from Microsoft that opens a real browser, such as Chrome or Firefox, and clicks through your app the way a user would., Cypress or Puppeteer.
