【问题标题】:Sinon: force callback callSinon:强制回调调用
【发布时间】:2017-04-28 12:03:40
【问题描述】:

我正在用这段代码测试一个函数:

return new Promise((ok, fail) => {
  this.repository.findById(id, (error, result) => {
    if (error)
      return fail(error);
    ok(result);
  });
});

我想测试失败的路径,即findById 方法调用回调时出错。我正在使用 sinon 为我的 repository 及其 findById 方法生成存根,但我不知道如何强制存根使用所需参数调用回调

以前有人做过这样的事吗?

谢谢

【问题讨论】:

  • 你用的是哪个sinon版本?

标签: node.js sinon


【解决方案1】:

使用Sinon 2,您可以使用存根的callsFake 方法:

sinon.stub(repository, 'findById').callsFake((id, callback) =>
    callback(new Error('oops'))
);

参见 Sinon 2 文档:http://sinonjs.org/releases/v2.1.0/stubs/

【讨论】:

  • ? 很高兴为您提供帮助!
【解决方案2】:

这里有一个更通用的答案: 每次我必须存根回调时,我都会这样做

const stubFindId = sinon.stub(repository, 'findById');    
stubGetitem.callsFake((value: string, callback: any) => {
      return callback(true, false);
    });

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 2017-09-25
    • 2017-10-24
    • 2016-12-23
    • 1970-01-01
    • 2021-04-15
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多