How to Fix act Warning in React Test Quickly and Easily
act warning in React tests happens when state updates or effects are not wrapped inside act, which ensures all updates finish before assertions. To fix it, wrap your rendering and updates inside act or use testing utilities like render and fireEvent from React Testing Library that handle act automatically.Why This Happens
The act warning appears because React wants to make sure all updates related to rendering, state changes, or effects are finished before you check the output in your tests. If you update state or trigger effects without wrapping them in act, React warns you that your test might be checking incomplete UI or state.
import { render, fireEvent } from '@testing-library/react'; import Counter from './Counter'; test('increments counter', () => { const { getByText } = render(<Counter />); const button = getByText('Increment'); fireEvent.click(button); // triggers state update expect(getByText('Count: 1')).toBeInTheDocument(); });
The Fix
To fix the warning, wrap any state updates or rendering inside act. If you use React Testing Library's render and fireEvent, they usually handle act for you. But if you manually update state or use async code, wrap those calls in await act(async () => { ... }).
import { render, fireEvent } from '@testing-library/react'; import { act } from 'react-dom/test-utils'; import Counter from './Counter'; test('increments counter with act', () => { const { getByText } = render(<Counter />); const button = getByText('Increment'); act(() => { fireEvent.click(button); }); expect(getByText('Count: 1')).toBeInTheDocument(); });
Prevention
Always use testing utilities like React Testing Library that wrap updates in act automatically. For manual state updates or async effects, wrap them in act. Use async/await with act for promises. Enable lint rules like react-hooks/exhaustive-deps and react-testing-library/await-async-utils to catch missing act usage early.
Related Errors
Other common errors include:
- Warning about state updates on unmounted components: Happens if cleanup is missing in effects.
- Async state updates not awaited: Fix by using
await act(async () => { ... }). - Legacy testing patterns: Avoid using
ReactTestUtilsdirectly withoutact.
Key Takeaways
act during tests to avoid warnings.render and fireEvent which handle act automatically.await act(async () => { ... }) to wait for all changes.act usage early and keep tests reliable.act wrapping.