Search code examples
javascriptreactjsunit-testingjestjsenzyme

Wait for fetch() to resolve using Jest for React test?


In my componentDidMount of a React.Component instance I have a fetch() call that on response calls setState.

I can mock out the request and respond using sinon but I don't know when fetch will have resolved it's promise chain.

componentDidMount() {
  fetch(new Request('/blah'))
    .then((response) => {
      setState(() => {
        return newState;
      };
    });
}

In my test using jest with enzyme:

it('has new behaviour from result of set state', () => {
  let component = mount(<Component />);

  requests.pop().respond(200);

  component.update() // fetch() has not responded yet and
                     // thus setState has not been called yet
                     // so does nothing

  assertNewBehaviour(); // fails

  // now setState occurs after fetch() responds sometime after
});

Do I need to flush the Promise queue/callback queue or something similar? I could do a repeated check for newBehaviour with a timeout but that's less than ideal.


Solution

  • The best answer it seems is to be use a container pattern and pass down the API data from a container class with separated concerns and test the components separately. This allows the component under test to simply take the API data as props and makes it much more testable.