score:184

Accepted answer

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.

score:1

while the pseudo code can be refactored to follow React lifecycle (using componentWillMount() componentDidMount(), it would be much easier to test. However, below is my untested pseudo code to the changes for your test codes, feel free to test it out and update it. Hope it'll help you!

describe('When rendering Parent', () => {
    it('should display Child with the response of the service', function(done) => {
        const parent = mount(<Parent />);
        expect(parent.html()).toMatch('fakeReturnValue');
        done();
    });
});

score:2

I'm unaware of anything native to React to accomplish what you're looking for.

However, I was able to accomplish this in similar code by calling beforeAll()'s @done after setup was complete. See changes to your code below:

let setupComplete;
jest.mock('eternalService', () => {
    return jest.fn(() => {
        return { doSomething: jest.fn((cb) => { cb('fakeReturnValue'); setupComplete(); }) };
});
.
.
.
    beforeAll(done => {
        parent = mount(<Parent />)
        setupComplete = done;
    });
});

I've never used them, but of potential interest is Jest's runAllTicks and runAllImmediates.

score:3

As an alternate to some of the techniques listed in other answers, you can use also use the npm module flush-promises. A sample test suite with two tests is shown below (as is also shown at the referenced url):

const flushPromises = require('flush-promises');

describe('Async Promise Test Suite', () => {

    it('A test involving flushPromises', async () => {
        const wrapper = mount(<App/>);
        await flushPromises();
        // more code
    });

    it('Will not work correctly without flushing promises', async () => {
        let a;
        let b;

        Promise.resolve().then(() => {
            a = 1;
        }).then(() => {
            b = 2;
        })

        await flushPromises();

        expect(a).toBe(1);
        expect(b).toBe(2);

    });

});

score:3

the flushPromises approach is in some scenario's broken.

Simply use await Promise.resolve() instead:

const component = mount(<App/>);

component.find('<button>').simulate('click');

// State changes

await Promise.resolve();

// Assert changes that occurred on the component

score:4

I would suggest you export aThingThatReturnsAPromise() from its module or file and then import it into your test case.

Since aThingThatReturnsAPromise() returns a promise, you can make use of the asynchronous testing features of Jest. Jest will wait for your promise to resolve and then you can make your assertions.

describe('When rendering Parent', () => {
    var parent;

    beforeAll(() => {
        parent = mount(<Parent />)
    });

    it('should display Child with response of the service', () => {
        expect.assertions(1);

        return aThingThatReturnsAPromise().then( () => {
            expect(parent.html()).toMatch('fakeReturnValue');
        });
    });
});

For more info, read how Jest handles test cases with Promises in the Jest Docs here


Related Query

More Query from same tag