In Enzyme how to wait for an API call in the componentDidMount method?

367 views Asked by At

We have a React component which we mount with Enzyme:

const component = mount(<App/>);

The component loads data on componentDidMount which we mock with nock:

nock('http://localhost:3100').get(`/api/data`).reply(200, DATA...);

We want to test the value of a label inside the component. However the value is only populated after the data is loaded via the fetch call. How can we wait for the fetch call to finish before writing the expect:

expect(...
1

There are 1 answers

0
Nahush Farkande On

You would have to do something like:

Promise
    .resolve(mounted)
    .then(() => mounted.update())
    .then(() => {
        expect(label === value); // Just using pseudocode here to denote where to write the expect statement
    })

You might still face incorrect behavior here, in which case you can check this thread