【问题标题】:How to make sinon mock return different objects on different calls?如何让 sinon mock 在不同的调用中返回不同的对象?
【发布时间】:2019-07-19 11:18:29
【问题描述】:
 mock = sinon.mock();
 mock.exactly(2);
 mock.callsArgWith(1, m1);
 mock.callsArgWith(1, m2);

在我的测试中,m2 覆盖了 m1。我想在第一次通话中返回 m1,在第二次通话中返回 m2。

怎么做?

【问题讨论】:

    标签: node.js unit-testing mocking sinon spy


    【解决方案1】:

    您可以使用onCall(n)(或别名onFirstCallonSecondCallonThirdCall)来定义第n次调用的行为:

    import * as sinon from 'sinon';
    
    test('mock returns different objects on different calls', () => {
      const m1 = { id: 1 }
      const m2 = { id: 2 }
    
      const mock = sinon.mock();
      mock.exactly(2);
      mock
        .onFirstCall().callsArgWith(1, m1)    // first call calls its second arg with m1
        .onSecondCall().callsArgWith(1, m2);  // second call calls its second arg with m2
    
      const spy = sinon.spy();
      mock('arg0', spy);  // spy should be called with m1
      mock('arg0', spy);  // spy should be called with m2
    
      sinon.assert.calledWithExactly(spy.getCall(0), m1);  // SUCCESS
      sinon.assert.calledWithExactly(spy.getCall(1), m2);  // SUCCESS
      mock.verify();  // SUCCESS
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 2018-03-24
      • 2022-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多