首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >redux-saga-test-plan:使用expectSaga模拟抛出的异常

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

Stack Overflow用户
提问于 2019-10-15 11:39:53
回答 1查看 2.4K关注 0票数 2

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

代码语言:javascript
复制
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返回异常的情况创建一个单元测试。

代码语言:javascript
复制
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只为call方法返回一个值,而不是抛出new Error对象。因此,错误对象不会被捕获。如何模拟抛出错误操作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-15 16:12:00

事实证明,它可以通过redux-saga-test-plan中的throwError()实现

代码语言:javascript
复制
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
        });
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58386912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档