react test_error ai_generated true

Warning: An update to X inside a test was not wrapped in act(...)

ID: react/act-warning

Also available as: JSON · Markdown
88%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
18 active

Root Cause

React state update in test not wrapped in act(). Test may not reflect final UI state.

generic

Workarounds

  1. 92% success Wrap state-triggering actions in act(): await act(async () => { fireEvent.click(btn) })
    await act(async () => { fireEvent.click(btn) })

    Sources: https://react.dev/reference/react/act

  2. 95% success Use React Testing Library's built-in methods (click, type) which auto-wrap in act
    import { render, screen, fireEvent } from '@testing-library/react';

    Sources: https://testing-library.com/docs/react-testing-library/intro/

  3. 90% success For async updates, use waitFor: await waitFor(() => expect(element).toBeVisible())
    await waitFor(() => expect(element).toBeVisible())

    Sources: https://testing-library.com/docs/dom-testing-library/api-async#waitfor

Dead Ends

Common approaches that don't work:

  1. Suppress console.error in tests 80% fail

    Silences the warning but test assertions may be wrong

  2. Add act() around every single assertion 55% fail

    Over-wrapping — only wrap state-changing operations

Error Chain

Frequently confused with: