You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Saga Test Plan如何为相同call的多次调用设置不同返回值

解决方法

你可以通过 Redux Saga Test Plan 内置的 sequence 工具实现按调用顺序返回不同结果的需求,配合 throws 标记需要抛出错误的调用场景即可。

完整修改后的测试代码

首先导入需要的辅助工具:

import { expectSaga, sequence, throws } from 'redux-saga-test-plan';

修改测试用例的 provide 配置:

it("must succeed after the first two requests are failures", () =>
  expectSaga(
    sagaToTest
  ).provide([
      [
        call(getdata, request),
        // 按调用顺序返回对应结果:前两次抛出错误,第三次返回成功值
        sequence([
          throws(new Error("oops")),
          throws(new Error("oops")),
          // 替换为你接口成功时实际返回的 mock 数据
          { result: "success data" }
        ])
      ]
    ])
    .call(getdata, request)
    .call(getdata, request)
    .call(getdata, request)
    .put(actions.itSucceeded("message"))
    .run());
});

自定义实现方案(不需要引入额外工具)

如果不想用内置的 sequence,也可以通过闭包维护调用计数来实现相同效果:

it("must succeed after the first two requests are failures", () => {
  // 维护调用次数计数
  let getdataCallCount = 0;

  return expectSaga(sagaToTest)
    .provide([
      [
        call(getdata, request),
        () => {
          getdataCallCount++;
          if (getdataCallCount <= 2) {
            throw new Error("oops");
          }
          return { result: "success data" };
        }
      ]
    ])
    .call(getdata, request)
    .call(getdata, request)
    .call(getdata, request)
    .put(actions.itSucceeded("message"))
    .run();
});

原理说明

当你给 provide 匹配规则的第二个参数传入函数时,每次对应 call 被触发都会执行这个函数,函数的返回值会作为 call 的执行结果,函数内抛出的错误会作为 call 的报错传递给 saga 逻辑。sequence 只是库提供的语法糖,内部也是通过计数来按顺序返回数组内的对应值,throws 工具用来标记当前次调用需要抛出错误,而不是把错误实例作为普通返回值处理。

内容的提问来源于stack exchange,提问作者nbpeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:45:00