The act() function

The act() function is probably the weirdest concept to learn when starting to write React tests.

If you are manually triggering some state change, then you should wrap your code in act().

If you don't, you will see a console warning.

Note: in the majority of tests, you will not have to use act(). The built-in helpers (like userEvent.click()) use it anyway.

There are actually two act() functions. One exported from React:

import { act } from 'react';

And one from React Testing Library (RTL):

import {
  render,
  act,
} from '@testing-library/react';

You should almost always use the one from RTL

But also you should be aware that you shouldn't need to use it too often.

Read on to find out more!

Loading full lesson content & code...

Ready to try running tests for this lesson?