How to make Jest wait for all asynchronous code to finish execution before expecting an assertion

Updated for Jest 27+

For jest 27+, you can also use process.nextTick:

await new Promise(process.nextTick);

(Thanks to Adrian Godong in the comments)

Original Answer

Here’s a snippet that waits until pending Promises are resolved:

const flushPromises = () => new Promise(setImmediate);

Note that setImmediate is a non-standard feature (and is not expected to become standard). But if it’s sufficient for your test environment, should be a good solution. Its description:

This method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.

Here’s roughly how to use it using async/await:

it('is an example using flushPromises', async () => {
    const wrapper = mount(<App/>);
    await flushPromises();
    wrapper.update(); // In my experience, Enzyme didn't always facilitate component updates based on state changes resulting from Promises -- hence this forced re-render

    // make assertions 
});

I used this a lot in this project if you want some working real-world examples.

Leave a Comment