【问题标题】:check nth call in Sinon stubbed method检查 Sinon 存根方法中的第 n 个调用
【发布时间】:2017-08-22 06:02:10
【问题描述】:

假设我有一个辅助方法helper.someFn 和服务方法servMethod 多次调用helper.someFn。现在在测试servMethod 时,我存根helper.someFn

// helper.js
exports.someFn = (param) => {
    return param + 1;
}


// service.spec.js
describe('Spec', () => {
    it('first test', (done) => {
        var someFnStub = sinon.stub(helper, 'someFn', (param) => {
            return 0;
        });
        // do servMethod call which calls someFn
        expect(someFnStub.firstCall.calledWith(5)).to.be.true;

        helper.someFn.restore();
        done();
    });
});

假设servMethod 已调用helper.someFn 5 次,每次使用不同的参数。在测试内部,我可以使用someFnStub.firstCall 访问helper.someFn 的第一个呼叫。我可以通过这种方式访问​​到第三次通话。如何访问下一个呼叫,例如第 4 次或第 5 次呼叫?

【问题讨论】:

    标签: node.js mocha.js sinon


    【解决方案1】:

    stub.onFirstCall()stub.onCall(0)的缩写,stub.onSecondCall()stub.onCall(1)的缩写等等,所以如果你想测试第四次调用:

    expect(someFnStub.onCall(3).calledWith(5)).to.be.true;
    

    在此处记录:http://sinonjs.org/releases/v3.2.1/stubs/#stub-onCall

    【讨论】:

    • 有趣的是,我刚刚看到我使用的是旧版本的 sinon ^1.17.7。我在legacy.sinonjs.org/docs 中找到了它的文档,在我的情况下,onCall 不起作用,而getCall 确实起作用了。
    • @RazinTanvir 很奇怪,因为文档指出 onCall 是在 1.8 中添加的,而您使用的是更高版本。
    • OP 想要检查第 n 次调用的参数和结果——但链接的 onCall() 建议指定结果将是什么,每个链接的文档:Defining stub behavior on consecutive calls [...] As of Sinon version 1.8, you can use the onCall method to make a stub respond differently on consecutive calls. 建议 getCall() 代替,如所示@GeriTol:stackoverflow.com/a/57890296/250988 例如,var spyCall = spy.getCall(n); Returns the nth call. -- sinonjs.org/releases/v9.0.2/spies
    • @DavidVMcKay 你是对的,onCall 用于更改运行时行为,而getCall 可以在事后调用,并且确实是 OP 要求的。
    【解决方案2】:

    源代码显示firstCallsecondCallthirdCall实际上只是getCall的糖。

    // lib/sinon/spy.js
        // ...
        this.firstCall = this.getCall(0);
        this.secondCall = this.getCall(1);
        this.thirdCall = this.getCall(2);
        this.lastCall = this.getCall(this.callCount - 1);
        // ...
    

    所以要在第四次调用中断言,您将使用stub.getCall(3)

    【讨论】:

      【解决方案3】:

      getCall(-nth) 其中nth 可以是负值。

      这允许从数组末尾索引调用:

      spy.getCall(-1) // returns the last call
      spy.getCall(-2) // the second to last call.
      // ...
      

      文档:https://sinonjs.org/releases/latest/spies/

      【讨论】:

        猜你喜欢
        • 2016-12-16
        • 1970-01-01
        • 1970-01-01
        • 2016-02-18
        • 2017-06-29
        • 2021-06-10
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        相关资源
        最近更新 更多