Reputation: 26729
I'm doing my first steps with testing React functional components with something like:
import React from 'react';
import { render } from '@testing-library/react';
import { act } from 'react-dom/test-utils';
import App from './App';
test('basic app rendering', () => {
act(() => {
render(<App />);
})
});
However this is resulting in the infamous warning that we have to use act
:
Warning: An update to SomeSubComponent inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
The link brings me back to where I'm coming from, and basically shows an example that is using act
exactly like I do.
I see a few possibilities:
act
.Any ideas what could lead to this situation that I get the "not wrapped in act" warning despite already wrapping in act
?
Upvotes: 3
Views: 1178
Reputation: 26729
It turned out that I simply needed this:
test('basic app rendering', async () => {
await act(async () => {
render(<App />);
})
});
This has been raised as an issue in version 16.8. Similar to that linked issue, my problem was an async function in useEffect
.
In versions 16.9+ onwards (I'm on 17.0) an async version of act
is available.
The reason I had asked the question is that I first made a stupid mistake trying the async variant:
test('basic app rendering', async () => {
await act(() => { // note missing async here
render(<App />);
})
});
I.e., I forgot to annotate the function passed to act
as async
as well. In this case it doesn't work (and in fact there is a warning 'await' has no effect on the type of this expression.
).
Upvotes: 5