Use this helper function to flush (run) all your promises - wrapped in RTL's act()
#async#promises#testing-library
Sometimes it can be useful to await until all currently queued Promises and microtasks have been processed.
(Note: this flushes the microtask queue by scheduling a new macrotask with setTimeout, allowing any pending Promise callbacks to execute before continuing)
import { act } from '@testing-library/react';
// wrapped in React's act(). If you aren't
// testing React you can remove the act part!
const flushPromises = async () => {
await act(async () => new Promise(resolve => setTimeout(resolve, 0)));
};
Use it like this:
// component automatically fetches data on initial render
render(<SomeComponent />);
await flushPromises();
expect(window.fetch).toHaveBeenCalledTimes(1);