Why does react hook throw the act error when used with fetch api?
For anyone who stumbles upon this more than a year later as I did, the issue Giorgio mentions has since been resolved, and wait
has since been replaced with waitFor
, as documented here:
https://testing-library.com/docs/dom-testing-library/api-async/
That being the case, I believe the solution to the warning now should be something like this:
import { render, waitFor } from '@testing-library/react';
// ...
it('should clear select content item', async () => {
fetch.mockResponseOnce(JSON.stringify({ results: data }));
const { container } = render(<App />);
const content = container.querySelector('.content');
await waitFor(() =>
expect(content.querySelectorAll('.content--item').length).toBe(2);
);
});
In my case, I had an App
component loading data asynchronously in a useEffect
hook, and so I was getting this warning on every single test, using beforeEach
to render App
. This was the specific solution for my case:
beforeEach(async () => {
await waitFor(() => render(<App />));
});
It's a known problem, check this issue in Github https://github.com/kentcdodds/react-testing-library/issues/281