How to use act() in React Testing Library?
On This Page What is act () in the React Testing Library?May 15, 2026 · 8 min read · Testing Guide
is a popular tool for quiz React components. It helps you write tests that interact with components like existent users, including clicking buttons, fill out forms, and checking the provide yield. When writing tests in the React Testing Library, you might have encountered warnings like & # 8220; An update to Counter inside a exam was not wrapped in act (). & # 8221; This usually happen when React tries to update the UI, but the trial isn & # 8217; t properly handling those update. That ’ s where act () arrive in. This article explains what act () does, why it ’ s needed, and how to use it effectively to forefend exam monition and ensure reliable termination. act () is a special helper function in the React Testing Library that secure all updates related to a factor are completed before assertions are create in a test. React updates the UI in batches and care them asynchronously. This entail the test might check the UI before it & # 8217; s fully update, leave to unexpected upshot or failures. act () helps with this by making sure React finishes all updates before the trial moves on. Without act (), you might get warning and because your component updates aren ’ t being handled properly. Read More: Using act () is necessary to ensure your execute as expect without warnings or flaky termination. Here are some scenarios where apply act () is important: If you cut using act (), your tests might deport unpredictably. Here ’ s what can happen: act () is used whenever your examination involves change to component ’ s state, issue, or UI updates. This is important because React updates the UI asynchronously, which intend changes don ’ t always happen instantly. If your test checks the UI too soon, it might fail or produce unreliable results. For example, if a button click update text on the blind, but the test checks text before React has stop processing the update, you might get an outdated value. Using act () hither ensures that React discharge all update before the test verify the result. Read More: When, not use act () in some situations can result to warning and eccentric tests. Let ’ s go measure by measure to translate this better. Here ’ s a simple counter portion that increments the reckoning when the button is clicked. For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users. If you indite a test without act (), you might get a monition and inconsistent test results. Running this test might produce this monition: In this exam, fireEvent.click (button) trigger a province update, but the assertion (expect (screen.getByText (& # 8220; Count: 1 & # 8221;))) might run before React has finished process the update. This can make flaky tryout, where sometimes the test passing, and other times it fails. To fix the above warning, you can wrap the state-changing activeness inside the act () Using act (), you tell React to complete all updates before the exam checks the UI. This helps continue tests reliable and prevents unexpected failure. Read More: When testing asynchronous operation like API calls, timers, or delay UI updates, React may direct some time to process change. If your test check the UI before these update are complete, it can lead to flaky results. Wrapping async actions inside act () ensures React finishes processing before the test move forward. Here ’ s an example of using act () for asynchronous updates: Whenever testing asynchronous demeanour, wrap updates inside act (async () = & gt; {& # 8230;}) ensures your tests wait for React to end updating before making assertions. To compose stable and dependable tryout in the React Testing Library, follow these best drill when habituate act (): 1. Use act () for State and Effect Updates: Whenever a test triggers a province modification or an event like an API call or a timeout, wrap the action inside act (). This check React treat updates before the test check the UI. 2. Use await act () for Asynchronous Updates:For async operation like API phone, timeouts, or stay province update, use await act (async () = & gt; {& # 8230;}). 3. Use findBy Queries for Auto-Waiting: If your tryout regard UI updates that take time, findBy queries in the React Testing Library automatically look for elements to appear. This means you don ’ t always need to use act (). 4. Use Built-in RTL Utilities: React Testing Library ’ s fireEvent and userEvent often handle act () automatically. But if a warning still appear, you can manually wrap them inside act (). 5. Avoid Overusing act (): You don ’ t invariably need to use act (). If your test doesn ’ t trigger state changes or effects, React Testing Library usually manage update on its own. Only use act () when you see warnings or discrepant examination results. Testing topically may not always speculate. Once you & # 8217; ve ensured your tests are stable with act (), it & # 8217; s essential to verify that your React application works seamlessly across different environments. With, you can test React applications on real browser and device, identifying UI repugnance that may not surface in a local setup. Using act () in the React Testing Library facilitate proceed your tryout stable and reliable by ensuring React finishes all update before checking the UI. You don ’ t always require it, but it ’ s important when work with state alteration, effects, or async updates. By following best practices like using act () when it & # 8217; s necessary, use findBy for async updates and guide reward of built-in RTL utilities, you can publish cleaner and more reliable tests. Testing your React coating on existent devices and browser is essential to ensure all real user conditions are considered while testing. BrowserStack ’ s real gimmick cloud allows you to run test on 3,500+ existent device and browser, supporting all major and tools for a seamless experience. Moreover, you can execute multiple tests simultaneously with, accelerating your test cycle. # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.How to use act () in React Testing Library?
What is act () in the React Testing Library?
Why Use act () in React Testing Library?
What hap if you don ’ t use act ()?
When to Use act () in React Testing Library?
Using act () in React Testing Library
import {useState} from `` react '';
map Counter () {
const [reckoning, setCount] = useState (0);
return (
& lt; div & gt;
& lt; p & gt; Count: {enumeration} & lt; /p & gt;
& lt; button onClick= {() = & gt; setCount (count + 1)} & gt; Increment & lt; /button & gt;
& lt; /div & gt;
);
}
exportation nonpayment Counter;Example Without act ()
import {render, screen, fireEvent} from `` @ testing-library/react '';
import Counter from `` ./Counter '';
tryout (`` increments counter on button click '', () = & gt; {
render (& lt; Counter / & gt;);
const button = screen.getByText (`` Increment '');
fireEvent.click (button);
expect (screen.getByText (`` Count: 1 '')) .toBeInTheDocument ();
});Warning: An update to Counter inside a test was not wrapped in act ().
Example With act ()
import {render, blind, fireEvent} from `` @ testing-library/react '';
import {act} from `` react-dom/test-utils '';
significance Counter from `` ./Counter '';
examination (`` increments counter on button dog '', () = & gt; {
render (& lt; Counter / & gt;);
const button = screen.getByText (`` Increment '');
act (() = & gt; {
fireEvent.click (push);
});
expect (screen.getByText (`` Count: 1 '')) .toBeInTheDocument ();
});Handling Asynchronous Code with act ()
import {render, screen} from `` @ testing-library/react '';
import {act} from `` react-dom/test-utils '';
import Counter from `` ./Counter '';
test (`` displays counting after delay '', async () = & gt; {
render (& lt; Counter / & gt;);
await act (async () = & gt; {
await new Promise ((resolve) = & gt; setTimeout (resolve, 1000));
});
expect (screen.getByText (`` Count: 1 '')) .toBeInTheDocument ();
});Better Practices for Using act () in React Tests
import {render, screen, fireEvent} from `` @ testing-library/react '';
import {act} from `` react-dom/test-utils '';
import Counter from `` ./Counter '';
test (`` increase counter on button click '', () = & gt; {
render (& lt; Counter / & gt;);
const button = screen.getByText (`` Increment '');
act (() = & gt; {
fireEvent.click (button);
});
expect (screen.getByText (`` Count: 1 '')) .toBeInTheDocument ();
});import {render, screen} from `` @ testing-library/react '';
import {act} from `` react-dom/test-utils '';
import Counter from `` ./Counter '';
test (`` displays count after delay '', async () = & gt; {
render (& lt; Counter / & gt;);
await act (async () = & gt; {
await new Promise ((settle) = & gt; setTimeout (conclude, 1000));
});
expect (screen.getByText (`` Count: 1 '')) .toBeInTheDocument ();
});expect (await screen.findByText (`` Count: 1 '')) .toBeInTheDocument ();
import {render, blind, fireEvent} from `` @ testing-library/react '';
significance {act} from `` react-dom/test-utils '';
import Counter from `` ./Counter '';
test (`` increments counter on button click '', () = & gt; {
render (& lt; Counter / & gt;);
const button = screen.getByText (`` Increment '');
act (() = & gt; {
fireEvent.click (button);
});
expect (screen.getByText (`` Count: 1 '')) .toBeInTheDocument ();
});Conclusion
Related Guides
Automate This With SUSA
Test Your App Autonomously