btholt / complete-intro-to-react

A Complete Intro to React, as Given for Frontend Masters
https://frontendmasters.com/learn/react/
MIT License
1.06k stars 929 forks source link

actionCreators.spec.js should call done.fail() on failure #75

Open epere4 opened 7 years ago

epere4 commented 7 years ago

On branch v3-26, test actionCreators.spec.js. you have this test:

test('getAPIDetails', (done: Function) => {
  const dispatchMock = jest.fn();
  moxios.withMock(() => {
    getAPIDetails(strangerThings.imdbID)(dispatchMock);
    moxios.wait(() => {
      const request = moxios.requests.mostRecent();
      request
        .respondWith({
          status: 200,
          response: strangerThings
        })
        .then(() => {
          expect(request.url).toEqual(`http://localhost:3000/${strangerThings.imdbID}`);
          expect(dispatchMock).toBeCalledWith(addAPIData(strangerThings));
          done();
        });
    });
  });
});

The problem is that if one of the expect fails, then the error the test reports is a timeout because you didn't call done().

I found that the done function has a subfunction called fail that you can call to report a failure. So, you need to do done.fail(error) when an error occurs.

Since you are in a then of a promise, adding a .catch(done.fail) should do it.

In other words, your test should be:

test('getAPIDetails', (done: Function) => {
  const dispatchMock = jest.fn();
  moxios.withMock(() => {
    getAPIDetails(strangerThings.imdbID)(dispatchMock);
    moxios.wait(() => {
      const request = moxios.requests.mostRecent();
      request
        .respondWith({
          status: 200,
          response: strangerThings
        })
        .then(() => {
          expect(request.url).toEqual(`http://localhost:3000/${strangerThings.imdbID}`);
          expect(dispatchMock).toBeCalledWith(addAPIData(strangerThings));
          done();
        }).catch(done.fail);  // Fail fast and with nice error in case of expectation failures.
    });
  });
});