2

I've got a React component which retrieves data using a Promise and then calls setState when the promise resolves. It then uses the updated state to change what's rendered.

When testing this, I use the testing library's findBy* methods to wait for the rendered component to have been updated with the content from the Promise:

await findByText("Failure details", { exact: false });

My tests pass - they correctly wait until the component has re-rendered. However, I get a warning like this when running them (I'm using Jest, but I don't think that's relevant):

Warning: An update to MyComponent inside a test was not wrapped in act(...).

Everything I've found online that's related to this is either about components using useEffect or about tests which include explicit calls to act in them (mine don't), which I don't think should be necessary here - my test itself isn't changing the component, apart from the fact that it calls render.

In short, my situation seems simpler than those that others are writing about - I'm just using setState and the findBy* queries, nothing more complex.

Is there an equally simple solution to this problem?

Sam
  • 5,997
  • 5
  • 46
  • 66

1 Answers1

0

Thankfully, the solution was simple - upgrading React and React-DOM to >= 16.9.0. I didn't have to change my tests or my component.

16.9.0 includes an asynchronous version of act. As I say, I didn't have to explicitly use it, but it was obviously being used behind the scenes because it solved my problem.

Sam
  • 5,997
  • 5
  • 46
  • 66
  • After fixing this problem as described here, I did actually end up wrapping the component code which calls `setState` in a `useEffect` hook so that I could do [cleanup](https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup) and not try and set state on an unmounted component. But that didn't require me to do anything further about the act warning, the above was still sufficient. – Sam Dec 12 '19 at 16:33