Reputation: 3058
How can I test the catch block of this action creator to reject the promise and to dispatch the error type & payload.
export const testMethod = async (dispatch: any) => {
try {
const result = await some API call
await dispatch({
payload: result,
type: SUCCESS_TYPE
});
return "success";
}
catch(error){
await dispatch({
payload: error,
type: ERROR_TYPE
});
return Promise.reject(error);
}
}
This is how I did for the try block.
it("should test try block", async () => {
jest
.spyOn(window, "fetch")
.mockReturnValueOnce(Promise.resolve({data: "something"}));
const dispatch = jest.fn();
const response = await testMethod()(dispatch);
expect(response).toEqual("success");
expect(dispatch.mock.calls.length).toBe(1);
expect(dispatch.mock.calls[0]).toStrictEqual([{
payload: response,
type: SUCCESS_TYPE
}]);
});
Similarly, I want to get full coverage on the catch block. Any help is greatly appreciated as I'm new to unit tests.
Upvotes: 0
Views: 2581
Reputation: 222548
It should be:
let error = new Error('foo');
jest.spyOn(window, "fetch").mockRejectedValueOnce(error);
await expect(testMethod()(dispatch)).rejects.toThrow(error);
expect(dispatch.mock.calls.length).toBe(1);
expect(dispatch.mock.calls[0]).toStrictEqual([{
payload: error,
type: ERROR_TYPE
}]);
Upvotes: 2