【问题标题】:When using Sinon, how to replace stub function in a stub instance?使用 Sinon 时,如何替换 stub 实例中的 stub 函数?
【发布时间】:2015-10-13 10:07:12
【问题描述】:

如果我通过var a = sinon.createStubInstance(MyContructor) 创建了一个实例。

如何替换 var stub = sinon.stub(object, "method", func); 等存根函数之一。

我这样做的主要原因是想实现多个回调解决方法,如this mentioned

【问题讨论】:

    标签: node.js mocha.js sinon nodeunit


    【解决方案1】:

    你提到的方法(sinon.stub(object, "method", func))是1.x版本中提供的方法,根据文档做了如下操作:

    object.method 替换为func,包裹在一个间谍中。像往常一样,object.method.restore();可以用来恢复原来的方法。

    但是,如果您使用的是sinon.createStubInstance(),则所有方法都已被存根。这意味着您已经可以对存根实例执行某些操作。例如:

    function Person(firstname, lastname) {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getName = function() {
      return this.firstname + " " + this.lastname;
    }
    
    const p = sinon.createStubInstance(Person);
    p.getName.returns("Alex Smith");
    
    console.log(p.getName()); // "Alex Smith"
    

    如果您真的想用另一个 spy 或 stub 替换 stub,您可以将该属性分配给一个新的 stub 或 spy:

    const p = sinon.createStubInstance(Person);
    p.getName = sinon.spy(function() { return "Alex Smith"; }); // Using a spy
    p.getName = sinon.stub(); // OR using a stub
    

    使用 Sinon.js 2.x 及更高版本,使用 callsFake() 函数更容易替换存根函数:

    p.getName.callsFake(function() { return "Alex Smith"; });
    

    【讨论】:

    • 在调用a.method = sinon.stub()之前,调用a.method.restore()很重要。
    • 投票赞成,因为这个答案让我走上了正轨。尽管自从回答了这个问题后,sinon.stub(object, "method", fn) 已被弃用。我们现在可以使用sinon.stub(object, "method").callsFake(function() { // do stuff }); 查看here Edit: fixed url
    • @PhilD。你是对的,但问题本身要求sinon.stub(object, "method", fn),所以我想我不会在答案本身中包含这些信息。
    • @g00glen00b,是的,但是每个来到这里的人都需要进行额外的迭代,才能返回代码,知道没有第三个参数,返回这里获取 cmets 或深入挖掘。我认为每个人都会从答案中的更新部分中受益
    • @KirillSlatin 在这个答案的原始状态和问题中,我发现很难整合它并且仍然保持问题的主题答案。但是,我试图重写答案,以便我可以将那部分整合到我的答案中。
    【解决方案2】:

    使用sinon.createStubInstance(MyConstructor)sinon.stub(obj) 存根整个对象后,您只能通过为属性分配新存根(如@g00glen00b 所述)或在重新存根之前恢复存根来替换存根。

    var a = sinon.createStubInstance(MyConstructor);
    a.method.restore();
    sinon.stub(object, "method", func);
    

    这样做的好处是您仍然可以在之后调用a.method.restore() 并获得预期的行为。

    如果 Stub API 有一个 .call(func) 方法来覆盖 stub 事后调用的函数会更方便。

    【讨论】:

      【解决方案3】:

      不需要覆盖a.method,我们可以直接在a.method上使用callsFake

      const a = sinon.createStubInstance(MyContructor);
      a.method.callsFake(func);
      

      【讨论】:

      • 使用了这种方法,效果很好。更简单更干净!
      • 太好了,很高兴你喜欢它!
      【解决方案4】:

      2.0 + 的另一种方法存根方法

      sinon.stub(object, "method").callsFake(func);
      
      object.method.restore()

      【讨论】:

        猜你喜欢
        • 2021-09-04
        • 1970-01-01
        • 2015-08-21
        • 1970-01-01
        • 2018-07-19
        • 2017-03-23
        • 1970-01-01
        • 2018-12-31
        • 2016-05-22
        相关资源
        最近更新 更多