Everything you need to know about act() in React tests

https://news.ycombinator.com/rss Hits: 1
Summary

When writing React tests, you will quickly become familiar with the act() function. Despite being a fundamental concept to testing your React apps, it is often one of the most confusing and misunderstood aspects of testing React applications. I've also in the past found it hard to articulate why we need it to engineers learning how to test their React apps. (But hopefully I clear it up for you in this page!). What is act(), why do we need it and when should you use it? In your tests, functionality that updates internal state of a rendered React component should be wrapped in act() so we can be sure that all state changes and side effects have been fully processed by React, before the rest of your test (i.e. assertions) continues. This makes sure that your tests are testing things in a realistic way (without it, you might be making assertions on 'old' state values, without realising). If you use React Testing Library (RTL) functions like the following, you don't have to think about act() as they already wrap their functionality in act(): user interaction with userEvent (like await userEvent.click(...)) the await findBy... functions like await screen.findByText("...") the waitFor(...) function But - there will definitely be times you will see the famous update was not wrapped in act() error that will plague your command line output if you are not careful. Understanding the "update was not wrapped in act(...)" error You have probably seen this a few times in your test result output: An update to %s 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 */ This is warning you that your tests are not wrapped in act(). This means you might be making assertions in your test against 'old' state and you might not notice or catch real bugs. (I've definitely ignored the warnings in the past, and introduced big bugs that were so eas...

First seen: 2026-01-16 05:19

Last seen: 2026-01-16 05:19