1
 mock = sinon.mock();
 mock.exactly(2);
 mock.callsArgWith(1, m1);
 mock.callsArgWith(1, m2);

Here in my test, m2 is overriding m1. I want to return m1 in my first call and m2 in my second call.

How to do that?

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

1 Answers1

2

You can use onCall(n) (or the aliases onFirstCall, onSecondCall, and onThirdCall) to define the behavior on the nth call:

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
});
Brian Adams
  • 43,011
  • 9
  • 113
  • 111