Successful Server Access

Learn what to do once we gain access to the server.

In the success scenario, we need to mock the axios library to return a successful response. We will be using the same mockRequest() utility introduced in the Async Action Creators lesson.

Our basic success tests need to check whether API_FINISHED is dispatched once the API is done. Test also check whether the success() action creator passes the response and is dispatched to the store once it is called.

// Success tests framework
describe('success', () => {
  beforeEach(() => mockRequest('recipes.json', 200, JSON.stringify(data)));

  it('should dispatch API_FINISHED');

  it('should dispatch SET_DATA');
});

A first attempt at testing the first case might look similar to the API_STARTED test:

// Testing that API_FINISHED is dispatched
it('should dispatch API_FINISHED', () => {
  middleware(apiAction());
  expect(dispatchCalls[2]).toEqual([{ type: API_FINISHED }]);
});

Unfortunately, this code will not work. We need to wait for API_FINISHED to be dispatched after the API’s promise is resolved before calling expect().

As discussed in “Async Action Creators,” we rely on our call to the middleware to return a promise that gets resolved once the network call completes. Only then can we run assertions and verify that everything behaved according to our expectations:

// The correct API_FINISHED test
it('should dispatch API_FINISHED', () => {
  return middleware(apiAction())
    .then(() => {
      expect(dispatchCalls[2]).toEqual([{ type: API_FINISHED }]);
    });
});

In this version of the test, we only check the array of calls to dispatch() once the promise returned by the call to middleware() is resolved. Since our new test is a one-liner, we can use some ES2015 magic and Jest’s toMatchSnapshot() method to shorten the code:

// Shorter API_FINISHED test
it('should dispatch API_FINISHED', () =>
   middleware(apiAction()).then(() =>
     expect(dispatchCalls[2]).toMatchSnapshot()));

Testing that the API middleware correctly sends the response from the server via the action creator provided in action.payload.success is very similar:

// Testing that SET_DATA was dispatched
it('should dispatch SET_DATA', () =>
  middleware(apiAction()).then(() =>
     expect(dispatchCalls[1]).toEqual([setData(data)])));

Once we make the network request, we check that the third call to dispatch() sent us the same action object as a direct call to the setData(data) action creator.

Remember that we mocked the server response for the axios library with mockRequest(), passing it the stringified version of data.

Get hands-on with 1200+ tech skills courses.