aicevas
Navigate back to the homepage
About

You Probably Don’t Need act() in Your React Tests

Tomas Zaicevas
Tomas Zaicevas
April 5th, 2021 · 6 min read
You Probably Don’t Need act() in Your React Tests

Originally published on Medium

TL;DR If you find yourself using act() with RTL (react-testing-library), you should see if RTL async utilities could be used instead: waitFor, waitForElementToBeRemoved or findBy.


React wants all the test code that might cause state updates to be wrapped in act().

But wait, doesn’t the title say we should not use act()? Well… Yes, because act() is boilerplate, which we can remove by using react-testing-library 🚀

What problem does act() solve?

Think about it this way: when something happens in a test, for instance, a button is clicked, React needs to call the event handler, update the state, and run useEffect. Since React state updates are asynchronous, React has to know when to do all of these things. That is why act() is necessary.

There is an amazing read if you want to dig deeper.

react-testing-library already wraps utilities in act()

Every time you use render(), userEvent, fireEvent they are already wrapped in act(). What does it mean, practically speaking?

It means that every time you use one of these utilities, all component’s relevant state updates are flushed. An additional synchronous act() is not going to change anything.

If you don’t believe me, take a look at this example:

1// App.js
2import { useState } from "react";
3
4const App = () => {
5 const [title, setTitle] = useState("");
6
7 const handleClick = () => {
8 setTitle("Clicked"); // act() in RTL render() makes this update happen
9 };
10
11 return (
12 <>
13 <button onClick={handleClick}>Click me</button>
14 {title}
15 </>
16 );
17};
18
19// App.test.js
20import { render, screen } from "@testing-library/react";
21import userEvent from "@testing-library/user-event";
22
23it("renders title when clicked", () => {
24 render(<App />); // this is wrapped in act()
25
26 userEvent.click(screen.getByRole("button"));
27
28 expect(screen.getByText("Clicked")).toBeInTheDocument();
29});
https://codesandbox.io/s/late-frost-3j2sr?file=/src/App.js

Note: all examples are based on a fresh create-react-app.

As you can see, we didn’t use act() and the new title is flushed after the click.

I mentioned synchronous act() for a reason. await act() is where things start to get tricky 🙊

😈 Asynchronous components

Whenever a state update is scheduled asynchronously (e.g. after a promise resolves), the test can no longer stay synchronous. Otherwise, React will warn us that state updates are not wrapped in act().

Let me illustrate what I mean. Instead of setting the title on button click, we’ll fetch it from an API:

1// App.js
2import { useEffect, useState } from "react";
3
4const App = () => {
5 const [title, setTitle] = useState("");
6
7 useEffect(() => {
8 const fetchData = async () => {
9 const response = await fetch(
10 "https://jsonplaceholder.typicode.com/posts/1"
11 );
12 const { title } = await response.json();
13
14 setTitle(title); // this happens after the test is done
15 };
16
17 fetchData();
18 }, []);
19
20 return <>{title}</>;
21};
22
23// App.test.js
24import { render, screen } from "@testing-library/react";
25
26it("renders title", () => {
27 jest.spyOn(window, "fetch").mockResolvedValue({
28 json: async () => ({ title: "Fetched" }),
29 });
30
31 render(<App />);
32
33 // this happens before the state update is scheduled
34 expect(screen.getByText("Fetched")).toBeInTheDocument();
35});
https://codesandbox.io/s/act-warning-7y357?file=/src/App.js

Not only does this test fail, but it also produces the infamous An update to App inside a test was not wrapped in act(...) warning.

act() warning

Why does this happen? The answer has more to do with the event loop than it does with React.

You might have noticed the test does everything synchronously. It does not have await or promise chains. For that reason, setTitle(title) goes into the task queue (also known as message queue) and is only executed after the call stack is clear. On the other end, expect(screen.getByText("Fetched")).toBeInTheDocument() goes into the call stack, which means it runs before the state update is scheduled!

Event loop visual
setTitle() goes into task queue, hence executes later than expect()

Okay, but why the warning, though? After all, render() causes the state update and it is wrapped in act() by RTL, so we should be good, right? 😧

Not really. Since render() is a synchronous function, it only flushes synchronous state updates.

To put it shortly:

  • The test fails because the state update is scheduled after the assertion.

  • The warning is printed because the state update is scheduled after the test is done.


How can this be solved?

🔴 Let me start with an incorrect example:

1it("renders title", async () => {
2 jest.spyOn(window, "fetch").mockResolvedValue({
3 json: async () => ({ title: "Fetched" }),
4 });
5
6 // DON'T DO THIS
7 await act(async () => {
8 render(<App />);
9 });
10
11 expect(screen.getByText("Fetched")).toBeInTheDocument();
12});
https://codesandbox.io/s/hide-act-warning-7e1b2?file=/src/App.test.js

This solves both our problems. It hides the warning and it also makes the test pass, but it brings other issues:

  • This only works because the state update happens in the next tick of the event loop.

  • act() does nothing special here, it merely hides the warning.

In fact, to show the hacky nature of this solution, take a look at another example. It also hides the warning and makes the test pass. It doesn’t look like it makes a lot of sense, right? Semantically, there is little difference between these two.

1it("renders title", async () => {
2 jest.spyOn(window, "fetch").mockResolvedValue({
3 json: async () => ({ title: "Fetched" }),
4 });
5
6 // DON'T DO THIS
7 render(<App />);
8 await act(async () => {});
9
10 expect(screen.getByText("Fetched")).toBeInTheDocument();
11});
https://codesandbox.io/s/hide-act-warning-2-r9tlq?file=/src/App.test.js

To prove my first point, This only works because the state update happens in the next tick of the event loop, consider an example in which we await for an additional promise.

1const fetchData = async () => {
2 const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
3 const { title } = await response.json();
4
5 await new Promise((resolve) => setTimeout(resolve, 0));
6
7 setTitle(title);
8};
https://codesandbox.io/s/hide-act-warning-3-oezlf?file=/src/App.js

It makes the tests fail!


✅ Use RTL async utilities instead

The good news is there is no need to use act() in these scenarios. We can use functions that come with RTL: waitFor, waitForElementToBeRemoved and findBy queries.

1it("renders title", async () => {
2 jest.spyOn(window, "fetch").mockResolvedValue({
3 json: async () => ({ title: "Fetched" }),
4 });
5
6 render(<App />);
7
8 expect(await screen.findByText("Fetched")).toBeInTheDocument();
9});
https://codesandbox.io/s/testing-async-the-proper-way-jvedu?file=/src/App.test.js

Or the waitFor variant:

1it("renders title", async () => {
2 jest.spyOn(window, "fetch").mockResolvedValue({
3 json: async () => ({ title: "Fetched" }),
4 });
5
6 render(<App />);
7
8 await waitFor(() => expect(screen.getByText("Fetched")).toBeInTheDocument());
9});
https://codesandbox.io/s/testing-async-the-proper-way-2-5b5qu?file=/src/App.test.js

Both variants pass and they don’t have the aforementioned issues.

Test passed

What if I fetch after an event?

There is no difference if asynchronously scheduled state update happens in useEffect or in an event handler. In the tests, instead of waiting for something to happen after render(), we can wait for something to happen after the event.

Let’s revisit the very first example, but this time we will update the state asynchronously:

1// App.js
2import { useState } from "react";
3
4const App = () => {
5 const [title, setTitle] = useState("");
6
7 const handleClick = async () => {
8 const response = await fetch(
9 "https://jsonplaceholder.typicode.com/posts/1"
10 );
11 const { title } = await response.json();
12
13 setTitle(title);
14 };
15
16 return (
17 <>
18 <button onClick={handleClick}>Click me</button>
19 {title}
20 </>
21 );
22};
23
24// App.test.js
25import { render, screen } from "@testing-library/react";
26import userEvent from "@testing-library/user-event";
27
28it("renders title when clicked", async () => {
29 jest.spyOn(window, "fetch").mockResolvedValue({
30 json: async () => ({ title: "Fetched" }),
31 });
32
33 render(<App />);
34
35 userEvent.click(screen.getByRole("button"));
36
37 expect(await screen.findByText("Fetched")).toBeInTheDocument();
38});
https://codesandbox.io/s/testing-userevent-the-proper-way-6zs7o?file=/src/App.test.js

As you can see, the fact that the state update is scheduled after the user’s click, rather than in useEffect, has not changed much from the test’s perspective. Wrapping userEvent in act() is as bad as wrapping render().

Are there cases when using act() is inevitable?

Yes, there might be certain scenarios. For instance, you might want to schedule a state update on a debounced function. In that case, using jest’s fake timers and wrapping jest.runAllTimers or jest.advanceTimersByTime in act() seems like a reasonable approach.

I suggest reading more about tricky cases here.

🚪 Conclusion

In most cases, react-testing-library makes wrapping test code in act() unnecessary. Furthermore, doing so might cause additional problems. Instead, try to make use of RTL async utilities and they should cover most of your needs.

There is already work going on to provide no-unnecessary-act rule in eslint-plugin-testing-library v4, but as of the time of writing this article, it is still a work in progress. Hopefully, it gets done soon.

I highly appreciate you taking your time reading this and I hope you’ve learned something new 🙂

Resources

The Most Important Assertions in Jest, React Testing Library Tests

The Most Important Assertions in Jest, React Testing Library Tests

Prioritize these assertions when writing component tests

March 31st, 2022 · 5 min read
How ESLint Resolves Plugins And Shareable Configs

How ESLint Resolves Plugins And Shareable Configs

And what does it have to do with package managers and peer dependencies?

February 22nd, 2022 · 3 min read
Copyright © 2023 Tomas Zaicevas
Link to $https://twitter.com/tozaicevasLink to $https://github.com/zaicevasLink to $https://linkedin.com/in/tomas-zaicevasLink to $https://zaicevas.medium.com/