Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing React: "Do not await the result of calling act(...) with sync logic"

Using react and react-dom 16.9.0

I am getting this warning when I'm testing my react hooks:

console.error node_modules/react-dom/cjs/react-dom-test-utils.development.js:80
Warning: Do not await the result of calling act(...) with sync logic, it is not a Promise.

My test code (using jest with @testing-library/react)

...
await act( () => {
  rerender(
    <HookTester
      promise={asyncFunction}
      initialValue={'extra loading...'}
    />
  );
});

expect(asyncFunction).toHaveBeenCalledTimes(2);
...

But if I don't await, then my expectation would be done too early.

like image 529
JulianG Avatar asked Sep 17 '19 09:09

JulianG


Video Answer


1 Answers

Oh! I got it!

It turns out the docs mention synchronous functions like this:

act( () => {
  // ... some 'sync logic'
});

which you can't await.

But you can await an async function of course:

await act( async () => {
  // ... some 'async logic'
});

This fixed the problem for me.

like image 133
JulianG Avatar answered Oct 07 '22 16:10

JulianG