Search code examples
typescriptredux-saga-test-plan

redux-saga-test-plan: use expectSaga to simulate an thrown exception


Inside my saga, I call an api request.

function* sendRequestSaga(): SagaIterator {
    yield takeEvery(Actions.sendRequest.type, sendApiRequest);
}

function* sendApiRequest(action: Action<string>) {
    try {
        yield call(/*args for calling api*/);
    } catch (error) {
        // Handle error
    }
}

I have created unit test for the success case. Now I want to create an unit test for the case that call api returns an exception.

it("Should handle exception correctly", () => {
    const expectedException = new Error("my expecting exception");
    return expectSaga(mySaga)
        .provide([
            [call(/*args for calling api*/), expectedException],
        ])
        .call(/*args for calling api*/)
        .dispatch({
            type: Actions.sendRequest.type,
            payload: /*args*/
        })
        .silentRun()
        .then(() => {
            // My assertion
        });
}

But this is not working cause provide only return a value for call method instead of throwing a new Error object. So, Error object is not caught. How can I simulate a throw Error action?


Solution

  • It turns out can be achieved by throwError() from redux-saga-test-plan

    import { throwError } from "redux-saga-test-plan/providers";
    
    it("Should handle exception correctly", () => {
        const expectedException = new Error("my expecting exception");
        return expectSaga(mySaga)
            .provide([
                [call(/*args for calling api*/), throwError(expectedException)],
            ])
            .call(/*args for calling api*/)
            .dispatch({
                type: Actions.sendRequest.type,
                payload: /*args*/
            })
            .silentRun()
            .then(() => {
                // My assertion
            });
    }