AI summary

What Jest, React Testing Library, jsdom and Playwright each do when you test React components, and what the act() warning actually means.

  • Jest runs the tests, React Testing Library renders and queries components, and jsdom imitates the browser.
  • Wait for async data with a findBy query, which retries until the element appears, and look elements up by their role, like button or heading, first.
  • act() belongs to React, and React Testing Library usually calls it for you.

The first thing that gets confusing with React tests is where one tool stops and the next one starts.

Jest runs the tests, React Testing Library renders your components and looks things up in them, and jsdom 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 Playwright, 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 jsdom and checks the output. An end-to-end test runs the whole app in a real browser.

What's real at each levelPick a test level.

Function test

Jest on its own is enough.

  • Jest runs the test and checks the result
  • DOM (removed)
  • Browser (removed)

Component test

Fast, but layout and navigation aren't real.

  • Jest runs the test
  • React Testing Library renders and queries (added)
  • jsdom: an imitation DOM inside Node (changed)
  • Layout and navigation (removed)

End-to-end test

Slow. Use it for critical flows like payments or signup.

  • Playwright, Cypress or Puppeteer (added)
  • A real browser, layout included (added)
  • Real routes, cookies and APIs (added)

What to install

Since React Testing Library 16, @testing-library/dom is a separate peer dependency, so you install it yourself next to the library. The library itself needs React 18 or 19.

Jest’s default environment is node, which has no DOM. For jsdom, install jest-environment-jsdom and select it with Jest’s testEnvironment option. In a Vite project, the vitest package can do the same job as Jest.

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.

Jest also can’t read JSX or import lines on its own. Babel translates your test files into plain JavaScript before Jest 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:

bash
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-react

Then two small config files, one for Babel and one that picks jsdom for Jest:

js
// babel.config.js
module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-react"],
};
js
// jest.config.js
module.exports = { testEnvironment: "jsdom" };

A simple Jest test

Jest 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.

js
// 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 mock that returns “hello there”, because in jsdom there’s no real server behind it:

jsx
// 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 Library docs put role queries first in their recommended order, because they’re closest to what users and screen readers see.

Since jsdom 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 Library. It batches render and state updates and finishes them before expect runs.

With and without act()Watch where expect lands in the order.

Without act()

expect can read a screen that hasn't updated yet.

  • first render
  • expect: reads the old screen (changed)
  • setState
  • render after setState

With await act()

expect runs once all the updates have finished.

  • first render
  • setState
  • render after setState
  • expect: reads the final screen (changed)

React Testing Library’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 Jest still prints this first:

text
  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:

jsx
test("shows 4 after a second", async () => {
  render(<Countdown />);
  expect(await screen.findByText("4", {}, { timeout: 1500 })).toBeInTheDocument();
});

This test passes without the warning:

text
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 Jest’s other name for test:

jsx
// 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 mock added, the other three tests in this article (sum, Fetch and act) pass on Jest 30, React 19 and React Testing Library 16:

text
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 total

Which kind of test to write

  • A plain function: Jest on its own.
  • A component’s output and interactions: Jest and React Testing Library on jsdom.
  • Layout, scrolling or a critical flow like payments or signup: a real browser, with Playwright, Cypress or Puppeteer.

References

  1. React act() documentation
  2. React 19 upgrade guide
  3. React Testing Library
  4. Testing Library query priority
  5. user-event setup
  6. Testing Library guiding principles
  7. Jest: using Babel
  8. Babel preset-react
  9. Jest testEnvironment option
  10. jsdom
  11. Playwright installation

Written by:

Full Stack Software EngineerSamsun, Türkiye

Full Stack Software Engineer. I started with client sites at an agency in 2019, then worked on embeds, a dashboard and analytics at a startup called Popupsmart.