jefflau/jest-fetch-mock

discussing about better support of React and act warning

sibelius opened this issue · 2 comments

https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning

console.error node_modules/react-dom/cjs/react-dom.development.js:530
  Warning: An update to UsernameForm 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://fb.me/react-wrap-tests-with-act
      in UsernameForm

We can get this warning when using jest-fetch-mock and React components

as jest-fetch-mock will update the React component outside React itself

we probably need to wrap the promise resolved by jest-fetch-mock inside act like this

await act(() => promise)

the problem is that fetchMock.mockResponseOnce does not return the promise that will be resolved

this API could help us

const promise = fetchMock.mockResponseOnce(
    JSON.stringify({
      data: {
        }
      },
    }),
  );

await act(() => promise)

This would completely change the usage of jest-fetch-mock and not something we're interested in doing.

This error message is more about how you write your tests than how Jest fetch mock operates. If you post a simple example we might be able to offer more assistance but we're not interested in changing the library as you've asked.

I fixed this using this code

await act(async () => {
    await new Promise((resolve) => setImmediate(resolve));
  });

it will flush all promises and react hooks