DEV Community

Patrick Geiger
Patrick Geiger

Posted on

React Unit Testing: Async Act

This is more or less for my own benefit as much as other people. Since starting my newest job last September, I've been knee deep in figuring out React testing with Enzyme and Jest. I'm not saying what I've got is the best way of doing things, but it works well enough.

So this will be the first of a series of different short articles where I describe methods of unit testing React.

We'll start with the async act. Act itself is rolled into a lot of Enzyme functions already, for example mount and simulate. So for the most part it's abstracted out if you use Enzyme.

But Enzyme just rolls in act, which is required if state changes happen. Without encompassing something that changes state in your component in act in a unit test, it throws an error. There are situations where you need to wait until the state change is entirely finished before continuing on. This is often found when using useEffect and setting state in that, especially if it sets the state that's required for the rest of the component. If you start looking at the component before useEffect has run its course, you might run into issues with things not looking how you'd expect them to.

This is where async act comes in.

import React from "react";

import { mount } from "enzyme";
import { act } from "react-dom/test-utils";

import MyComponent from "./MyComponent";

let wrap;
beforeEach(async () => {
  await act(async () => {
    wrap = mount(<MyComponent />);
  });
  wrap.update();
});

Let's pretend that MyComponent has a useEffect that sets some state. If you just use mount that state may not be set properly. On the other hand, if you use an async act like above? It will wait until the useEffect has finished running.

Make sure to call .update() as well so the React wrapper updates.

This was a major pain point for us where useEffects would not run as we expected them to. The async act solved a lot of these issues, and we didn't even know it existed until we updated our version of React. So I guess that's a good lesson for keeping up with the updates for the tools you use!

Top comments (0)