Testing Async Redux Action Jest

不羁的心 提交于 2019-12-06 15:50:01

I am using jest-fetch-mock and no axios. The following is working for me with the actions. You could refactor to async await as first step. For me it only worked that way.

I am now trying to figure out how to test the side effect (showErrorAlert(jsonResponse);). If I mock out the showErrorAlert implementation at the top of the test file (commented out in my example) then I get the same problem just like you. Actions that uses fetch won't get triggered for some reason.

export const submitTeammateInvitation = (data) => {
  const config = {
    //.....
  };

  return async (dispatch) => {
    dispatch(submitTeammateInvitationRequest());

    try {
      const response = await fetch(inviteTeammateEndpoint, config);
      const jsonResponse = await response.json();

      if (!response.ok) {
        showErrorAlert(jsonResponse);
        dispatch(submitTeammateInvitationError(jsonResponse));

        throw new Error(response.statusText);
      }

      dispatch(submitTeammateInvitationSuccess());
    } catch (error) {
      if (process.env.NODE_ENV === 'development') {
        console.log('Request failed', error);
      }
    }
  };
};

test

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

// jest.mock('../../../../_helpers/alerts', ()=> ({ showAlertError: jest.fn() }));

const middlewares = [thunk];
const createMockStore = configureMockStore(middlewares);

......

it('dispatches the correct actions on a failed fetch request', () => {
  fetch.mockResponse(
    JSON.stringify(error),
    { status: 500, statusText: 'Internal Server Error' }
  );

  const store = createMockStore({});
  const expectedActions = [
    {
      type: 'SUBMIT_TEAMMATE_INVITATION_REQUEST',
    },
    {
      type: 'SUBMIT_TEAMMATE_INVITATION_FAILURE',
      payload: { error }
    }
  ];

  return store.dispatch(submitTeammateInvitation(data))
    .then(() => {
      // expect(alerts.showAlertError).toBeCalled();
      expect(store.getActions()).toEqual(expectedActions);
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!