Hello,
I'm trying to test my React Application with React Testing Library and Jest but I always have the following error.
An update to StoreProvider inside a test was not wrapped in act(...)
I tried many things like put act() function around my test but can't be able to remove the warning and get the correct result.
Here's a simplified project that demonstate the problem:
https://codesandbox.io/s/adoring-haslett-6rq34?file=/src/PageContent.test.js
Thanks for your help.
Edit: See https://github.com/testing-library/react-testing-library/issues/641#issuecomment-615384747 for the correct answer.
A, more general, problem is that your component might try to update the state after it is unmounted. You can fix this with
```js
React.useEffect(() => {
let current = true;
asyncWork.then(() =>
if (current === true) dispatch();
})
return () => (current = false);
}, dependencies)
This is especially problematic if you have tests that fail. These will unmount your component before your async work had time to finish.
Either way this question is better suited for StackOverflow or spectrum. It's not an issue with react-testing-library.
This is not exactly correct. You should never have to wrap render in act and you should rarely need to use act directly.
You need to wait for the text (as @eps1lon suggests), but once you add that async util (which is automatically wrapped in act) the error goes away and there's no need for you to call act yourself.
But I much prefer the find* queries which use waitFor under the hood, so if I were writing this test, this is what I would do:
https://codesandbox.io/s/great-dijkstra-njz7k?file=/src/PageContent.test.js:232-317
render(<App />)
expect(await screen.findByText('STATUS = 0')).toBeInTheDocument()
And that's it :)
Thank you very much @kentcdodds & @eps1lon !
It' OK with await findByText.
As render already use act internally, I would prefer the second solution.
Here's my working piece of code.
const { findByText } = render(<App />)
expect(await findByText('STATUS = 0')).toBeInTheDocument();
Most helpful comment
This is not exactly correct. You should never have to wrap
renderin act and you should rarely need to useactdirectly.You need to wait for the text (as @eps1lon suggests), but once you add that async util (which is automatically wrapped in
act) the error goes away and there's no need for you to callactyourself.But I much prefer the
find*queries which usewaitForunder the hood, so if I were writing this test, this is what I would do:https://codesandbox.io/s/great-dijkstra-njz7k?file=/src/PageContent.test.js:232-317
And that's it :)