React testing-library Be sure to await previous act() calls before making a new one

Viewed 2356

I write a test for a seletion and I get this warning. In my test I'm waiting for the end of the act. Why I get this error?

Warning: You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one.

test('Selection should be have the correct number of options', async () => {
const leftClick = { button: 0 };
const { options } = makeSUT();
const selection = screen.getByLabelText('MultiSelection');

// open all option
act(() => {
  userEvent.click(selection, leftClick);
});
// await wait();

options.forEach(async (option, index) => {
  if (index === 0) {
    expect((await screen.findAllByText(option.label)).length).toEqual(1);
  } else {
    expect((await screen.findAllByText(option.label)).length).toEqual(1);
  }
});});

Thank you

1 Answers

userEvent utility API methods should not be wrapped in act(). It is recommended not to do so here. Instead, you can just await the method call. After you have performed an action, you can use waitFor to wait for the Component state to update and run your assertions. To simplify your logic, I would replace findBy with a waitFor and getBy so you're not having to async your forEach().

You should ensure you are setting up userEvent correctly (see here)

The following should resolve your issue:

test('Selection should be have the correct number of options', async () => {
    const user = userEvent.setup(); // Make sure to setup correctly.
    const leftClick = { button: 0 };
    const { options } = makeSUT();
    const selection = screen.getByLabelText('MultiSelection');
    
    // Wait for the userEvent to click:
    await user.click(selection, leftClick);
    waitFor(() => {
        options.forEach((option, index) => {
            if (index === 0) {
                expect((screen.getAllByText(option.label)).length).toEqual(1);
            } else {
                expect((screen.getAllByText(option.label)).length).toEqual(1);
            }
        });
    });
});
Related