38

I would like to re-stub someHandler.getStatus, but I'm getting TypeError: Attempted to wrap getStatus which is already wrapped ..

it('is a test', function() {

  sandbox.stub(someHandler, 'getStatus', function(callback) {
    callback(null, {
      value: 1
    });
  });

  sandbox.stub(someOtherHandler, 'doSomething', function(callback) {
    callback(null);
  });

  sandbox.stub(someHandler, 'getStatus', function(callback) {
    callback(null, {
      value: 0
    });
  });
});
bobbyrne01
  • 6,295
  • 19
  • 80
  • 150

2 Answers2

95

Sinon has a nice API for handling multiple calls (stub.onCall(n);) to the same stubbed method.

Example from stub api doc:

"test should stub method differently on consecutive calls": function () {
    var callback = sinon.stub();
    callback.onCall(0).returns(1);
    callback.onCall(1).returns(2);
    callback.returns(3);

    callback(); // Returns 1
    callback(); // Returns 2
    callback(); // All following calls return 3
}

You can also use onFirstCall() , onSecondCall(), and onThirdCall().

We are using this approach extensively in our tests.

Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
gor181
  • 1,988
  • 1
  • 14
  • 12
1

try tracking the calls using an external variable. first time it's called, return the first value and increment the counter. second call (and all subsequent calls), return the second value.

it('is a test', function() {

  let callCount = 0

  sandbox.stub(someHandler, 'getStatus', function(callback) {
    callback(null, {
      value: callCount++ == 0 ? 1 : 0
    });
  });

  sandbox.stub(someOtherHandler, 'doSomething', function(callback) {
    callback(null);
  });    
});

this is a simple example to handle 2 calls, but you expand it to handle multiple calls if needed.

Jeff M
  • 477
  • 2
  • 5
  • `sinon stub(obj, 'meth', fn) has been removed, see documentation`. This current syntax will do the same thing as above: `sandbox.stub(someHandler, 'getStatus').callsFake(() => callCount++ == 0 ? 1 : 0);`. – Andy Gout Nov 14 '19 at 13:07