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

使用Sinon.js Stub模拟函数抛异常并断言捕获问题求助

问题分析与修正方案

代码中的关键问题

  1. Sinon Stub 异常写法错误
    你写的retrieveConfig.withArgs(false).throws('testName'['optional message']);是无效语法,'testName'['optional message']会尝试取字符串索引,结果为undefined。另外,业务函数中用await调用retrieveConfig,属于异步场景,应该用rejects模拟Promise拒绝,而非同步的throws。

  2. 异步断言方式错误
    isCompliant是异步函数,不能直接用assert.throwsException(Node.js标准assert无此方法),且直接await会把异常抛出到外层,无法被断言方法捕获,需用assert.rejects来断言Promise被拒绝。

  3. 变量名不匹配
    测试代码调用isCompliant时传入的partnerProfileIdList,应该是你定义好的partnerList。

修正后的测试代码

t.test('Assert that thrown errors are caught if 401: unauthorized error is returned', async (st) => {
  // 用resolves/rejects模拟异步函数的状态
  let retrieveConfig = sinon.stub();
  retrieveConfig.withArgs(true).resolves(true);
  retrieveConfig.withArgs(false).rejects(new Error('unauthorized'));

  let partnerList = [true, false];

  const dataSources = {
    storageService: {
      retrieveConfig
    }
  };

  // 断言异步函数会抛出指定的401异常
  await assert.rejects(
    isCompliant(dataSources, partnerList),
    (err) => err === 401
  );

  st.end();
});

业务函数说明

你的业务函数逻辑是正确的:当retrieveConfig抛出异常时,会被catch块捕获并重新抛出401。只需注意,若retrieveConfig是异步函数,Stub必须用resolves/rejects模拟Promise状态,才能和await的行为匹配。

额外注意

  • 若使用chai这类第三方断言库,对应写法为return expect(isCompliant(...)).to.be.rejectedWith(401)。
  • 确保Sinon版本在2.0及以上,支持resolves和rejects方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:05:26