Reset “called” Count on Sinon Spy

This question was asked a while back but may still be interesting, especially for people who are new to sinon.

this.spied.reset() is not needed as Obj.prototype.spiedMethod.restore(); removes the spy.

Update 2018-03-22:

As pointed out in some of the comments below my answer, stub.reset will do two things:

  1. Remove the stub behaviour
  2. Remove the stub history (callCount).

According to the docs this behaviour was added in sinon@2.0.0.

The updated answer to the question would be to use stub.resetHistory().

Example from the docs:

var stub = sinon.stub();

stub.called // false

stub();

stub.called // true

stub.resetHistory();

stub.called // false

Update:

  • If you just want to reset the call count, use reset. This keeps the spy.
  • To remove the spy use restore.

When working with sinon you can use the sinon assertions for enhanced testing. So instead of writing expect(this.spied).to.have.been.calledOnce; one could write:

sinon.assert.calledOnce(Obj.prototype.spiedMethod);

This would work as well with this.spied:

sinon.assert.calledOnce(this.spied);

There are a lot of other sinon assertion methods. Next to calledOnce there are also calledTwice, calledWith, neverCalledWith and a lot more on sinon assertions.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)