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

使用sinon mock DynamoDB get调用时出现stub expected to yield报错如何解决

问题原因

你的测试代码中使用sinon.stub.yields()配置模拟返回,这个API仅适用于回调式调用的场景,而你的业务代码调用DynamoDB get接口后链式调用了.promise()走Promise异步逻辑,没有给get方法传入回调函数,因此sinon找不到预期的回调参数就抛出了该错误。

解决方法

修改测试代码中get stub的配置,让它返回一个包含promise方法的对象,匹配业务代码的调用逻辑:

  1. 删掉clientStub.get.yields(null, expectedData);
  2. 替换为让get方法返回带promise方法的对象,promise方法返回你预期的测试数据,注意要匹配业务代码读取result.Item的结构。

修改后的测试用例代码

it('should get random data!', async () => {
  const expectedData = "neeraj";

  // 配置stub:get方法返回带promise方法的对象
  clientStub.get.returns({
    promise: () => Promise.resolve({ Item: expectedData })
  });

  const data = await mut.run();

  sinon.assert.callCount(clientStub.get, 1);
  assert.strictEqual(data, expectedData);
});

可选优化

如果需要校验调用get方法时传入的参数是否正确,可以加上参数匹配校验:

clientStub.get.withArgs({
  TableName: 'employees',
  Key: { name: "naxi" }
}).returns({
  promise: () => Promise.resolve({ Item: expectedData })
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:15:03