redux-saga-test-plan:使用expectSaga模拟抛出的异常

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

在我的传奇中,我调用了一个 api 请求。

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
    }
}

我已经为成功案例创建了单元测试。现在我想为调用 api return 异常的情况创建一个单元测试。

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
        });
}

但这不起作用,因为 provide 只有 return call 方法的值,而不是抛出 new Error 对象。所以,错误对象没有被捕获。如何模拟抛出错误动作?

原来可以通过throwError()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
        });
}