Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React: An update inside a test was not wrapped in act(...)

The warning means a state update escaped the test's act scope. Await the interaction, use findBy queries, and wrap manual updates properly.

~6 min readReact
#React#Testing#Vitest#Debugging
A test runner block with a state pulse escaping a component cube, an amber warning plate and a cyan act clamp

Introduction & Quick Summary

An update to Counter inside a test was not wrapped in act(...) is a warning React prints when a state update escapes the boundary the test runner is watching. React is not sure the DOM reflects the update before the assertion runs, so the test may pass for the wrong reason or fail intermittently. The warning names the component, and it almost always appears in one of four situations: an async effect resolving after the test function returned, a state update triggered by a raw event dispatch outside userEvent, a timer advanced without wrapping, or a manual render call from an older React version.

The dependable fixes, in order of preference:

  • Await the user's action. await user.click(...) and await screen.findByText(...) wrap their own act, so most warnings disappear without an explicit act call.
  • Await the update you started. After fireEvent or a direct store update, use await waitFor(() => expect(...)) rather than a synchronous assertion.
  • Wrap deliberate manual updates in await act(async () => { ... }), not a bare act(() => ...) when promises are involved.
  • Use fake timers inside act. act(() => jest.advanceTimersByTime(1000)) flushes everything the timer queued.
  • Set IS_REACT_ACT_ENVIRONMENT in the test setup so React knows it is under a test runner at all.
SymptomLikely causeFix
Warning once, test still passesState update lands after the assertionReplace with findBy* or waitFor
Warning on every test in a fileMissing IS_REACT_ACT_ENVIRONMENT in setupAdd it to the jest/vitest setup file
Warning after fireEventFire-and-forget dispatch of an async handlerawait act(async () => fireEvent.click(...))
Warning only with fake timersTimer callback queued outside actAdvance inside act
act is not exportedImported from react-dom/test-utils on React 19Import from react

Core Mechanics, Signatures & Reproducible Setup

act is a hint to React that it should flush work — effects, microtasks, and the resulting renders — before control returns to you. The test renderer and React Testing Library call it for you inside render, userEvent and waitFor. The warning fires when a state update is scheduled while no act scope is open, and it only exists in test builds. In a real browser the same update is perfectly legal; the warning means the test cannot prove the DOM settled.

React 19 renamed the entry point: act comes from react, and react-dom/test-utils no longer exports it. React Testing Library 16 is the version that pairs with React 19. A minimal failing project needs only these pieces.

bash
npm create vite@latest act-demo -- --template react-ts cd act-demo && npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
{ "compilerOptions": { "jsx": "react-jsx", "types": ["vitest/globals"] }, "include": ["src"] }
ts
// src/setup.test.ts import "@testing-library/jest-dom/vitest"; import { cleanup } from "@testing-library/react"; import { afterEach } from "vitest"; globalThis.IS_REACT_ACT_ENVIRONMENT = true; afterEach(() => cleanup());

The component that produces the warning defers a state update:

tsx
export function Counter() { const [count, setCount] = useState(0); useEffect(() => { const id = setTimeout(() => setCount((c) => c + 1), 50); return () => clearTimeout(id); }, []); return <p>{count}</p>; }

The failing test asserts synchronously, so React schedules the update after the test body has finished:

tsx
it("increments after mount", () => { render(<Counter />); expect(screen.getByText("1")).toBeInTheDocument(); // warning, then failure });

The console output is explicit about the boundary:

text
Warning: An update to Counter inside a test was not wrapped in act(...). When testing, code that causes React state updates should be wrapped into act(...): act(() => { /* fire events that update state */ }); /* assert on the output */

Key Comparison Table

The useful judgment is not "which act workaround compiles" but which helper owns the flush. Each row below is a real API with different guarantees.

HelperWraps act itselfWaits for async workUse when
userEvent.clickYesYes, if awaitedRealistic interaction
fireEvent.clickNoNoNon-async handlers only
findBy* queriesYesYes, up to timeoutAppearance after a promise
waitForYesYes, retries assertionAnything converging over time
act(async () => ...)Yes (that is the call)Awaits the callbackManual store or timer control
renderHook resultRenders, not updatesNoPure hook unit tests

The second axis is the React version pair: React 17 imports act from react-dom/test-utils and ignores IS_REACT_ACT_ENVIRONMENT; React 18 keeps that import but requires the flag in setup; React 19 moves act to react and drops the old export, with RTL 16 as the matching release.

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Async assertions instead of synchronous ones

The smallest correct fix replaces the synchronous assertion with a query that retries inside act. No import of act is needed, and the test now proves the DOM settled.

tsx
it("increments after mount", async () => { render(<Counter />); expect(await screen.findByText("1")).toBeInTheDocument(); });

findByText runs inside waitFor, which wraps every retry in act, so the update is flushed before the match is evaluated. This is the pattern to reach for first: if waiting for something observable removes the warning, do that instead of reaching for act.

Manual updates need await act(async ...)

When a test drives a store, a router, or a third-party callback directly, nothing in the library knows an update is coming. Wrap the call, and make the callback async so React drains microtasks before the assertion.

tsx
it("reacts to an external store update", async () => { render(<Connected />); await act(async () => { store.setState({ value: 2 }); }); expect(screen.getByText("2")).toBeInTheDocument(); });

A synchronous act(() => store.setState(...)) fixes the render but not a follow-up promise, which is why the warning sometimes survives the first fix and returns one tick later.

Fake timers have to advance inside act

Jest or Vitest fake timers replace setTimeout, so the component's effect never runs until the test advances the clock — and advancing it outside act schedules a state update in no scope.

tsx
it("advances fake timers safely", async () => { vi.useFakeTimers(); render(<Counter />); await act(async () => { vi.advanceTimersByTime(60); }); expect(screen.getByText("1")).toBeInTheDocument(); vi.useRealTimers(); });

With user-event and fake timers together, pass advanceTimers so the library advances the clock itself: userEvent.setup({ advanceTimers: vi.advanceTimersByTime }). That option is the difference between a clean suite and a file full of warnings after migrating to Vitest.

Tell React it is under a test runner

Since React 18 the flag is opt-in. Without globalThis.IS_REACT_ACT_ENVIRONMENT = true, React either skips the warning entirely or prints it for updates act cannot see, which makes suites behave differently between Jest and Vitest. Set it once in the setup file listed by setupFiles, not per test, and call cleanup after each test so unmounted components do not update later.

ts
// vitest.config.ts export default defineConfig({ test: { environment: "jsdom", setupFiles: ["./src/setup.test.ts"], globals: true, }, });

Updates that arrive after the test ends

The stubborn case is a component whose promise resolves after the assertion. The warning names the component only once; later updates are silent. Make the test wait for the final state, or unmount explicitly with cleanup() so the update targets nothing.

tsx
it("waits for the fetch to settle", async () => { render(<Profile id="1" />); expect(await screen.findByText("ada")).toBeInTheDocument(); await waitFor(() => expect(screen.queryByText("Loading")).not.toBeInTheDocument()); });

Common Compilation/Runtime Mistakes & Version Gotchas

Importing act from react-dom/test-utils. On React 19 that module no longer re-exports it, so the build fails with has no exported member 'act'. Import from react, and check that @testing-library/react is 16 or newer.

Calling act from a non-test file. The warning disappears in production because act is a no-op there, but a component that calls it behaves differently in development and tests. Keep act in test utilities only.

Using setTimeout instead of waitFor. A fixed sleep hides the race on a fast machine and fails on a slow CI runner; waitFor retries, a sleep does not.

Wrapping render in act. render already calls it; double-wrapping nests scopes and React warns about overlapping act calls.

Forgetting await on userEvent. userEvent.click returns a promise in v14 and later. Without await, dispatch and assertion race, and the warning points at the component rather than the missing await.

Setting IS_REACT_ACT_ENVIRONMENT inside one test. Setup files run once per file, so mutating the flag in a single test leaks into the tests after it. Set it at module scope in the setup file.

Version matrix. React 18 with RTL 14 or 15 still works; RTL 16 requires React 18 or 19 and is the only supported pairing for React 19's act; Vitest needs globals: true or an explicit expect import for jest-dom matchers to type-check.

The warning is a symptom of a test that cannot observe the update, not of a broken component: fix the observation point and the message disappears. When reviewing a large test refactor, the diff tool keeps the act-related changes readable, and the JSON formatter checks the config files that wire the setup.

Official references: act in the React reference and the React 19 release post, which documents the moved export.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.