You can simulate the showErrorAlert function manually. Here is the solution:
actionCreators.ts :
import fetch from 'node-fetch'; import { showErrorAlert } from './showErrorAlert'; const SUBMIT_TEAMATE_INVITATION_REQUEST = 'SUBMIT_TEAMATE_INVITATION_REQUEST'; const SUBMIT_TEAMATE_INVITATION_SUCCESS = 'SUBMIT_TEAMATE_INVITATION_SUCCESS'; const SUBMIT_TEAMATE_INVITATION_ERROR = 'SUBMIT_TEAMATE_INVITATION_ERROR'; export const submitTeammateInvitationRequest = data => ({ type: SUBMIT_TEAMATE_INVITATION_REQUEST, payload: { data } }); export const submitTeammateInvitationSuccess = data => ({ type: SUBMIT_TEAMATE_INVITATION_SUCCESS, payload: { data } }); export const submitTeammateInvitationError = data => ({ type: SUBMIT_TEAMATE_INVITATION_ERROR, payload: { data } }); export const submitTeammateInvitation = data => { const config = {
showErrorAlert.ts :
export function showErrorAlert(jsonResponse) { console.log(jsonResponse); }
actionCreators.spec.ts :
import { submitTeammateInvitation, submitTeammateInvitationRequest, submitTeammateInvitationSuccess, submitTeammateInvitationError } from './actionCreators'; import createMockStore from 'redux-mock-store'; import thunk, { ThunkDispatch } from 'redux-thunk'; import fetch from 'node-fetch'; import { AnyAction } from 'redux'; import { showErrorAlert } from './showErrorAlert'; const { Response } = jest.requireActual('node-fetch'); jest.mock('node-fetch'); jest.mock('./showErrorAlert.ts', () => { return { showErrorAlert: jest.fn() }; }); const middlewares = [thunk]; const mockStore = createMockStore<any, ThunkDispatch<any, any, AnyAction>>(middlewares); describe('submitTeammateInvitation', () => { it('dispatches the correct actions on a failed fetch request', () => { const mockedResponse = { data: 'mocked response' }; const mockedJSONResponse = JSON.stringify(mockedResponse); const mockedData = { data: 'mocked data' }; (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce( new Response(mockedJSONResponse, { status: 500, statusText: 'Internal Server Error' }) ); const intialState = {}; const store = mockStore(intialState); const expectedActions = [ submitTeammateInvitationRequest(mockedData), submitTeammateInvitationError(mockedResponse) ]; return store.dispatch(submitTeammateInvitation(mockedData)).then(() => { expect(store.getActions()).toEqual(expectedActions); expect(showErrorAlert).toBeCalledWith(mockedResponse); }); }); });
Unit test result with coverage report:
PASS src/stackoverflow/47560126/actionCreators.spec.ts submitTeammateInvitation β dispatches the correct actions on a failed fetch request (11ms) -------------------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line
Here is the finished demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/47560126
slideshowp2
source share