How do I reset the "called" count on a Sinon spy before each test?
Here's what I'm doing now:
beforeEach(function() { this.spied = sinon.spy(Obj.prototype, 'spiedMethod'); }); afterEach(function() { Obj.prototype.spiedMethod.restore(); this.spied.reset(); });
But when I check the call count in a test:
it('calls the method once', function() { $.publish('event:trigger'); expect(this.spied).to.have.been.calledOnce; });
...the test fails and reports that the method was called X number of times (once for each previous test that also triggered the same event).
All you have to do is create a sandbox in the very first describe block so that, it is accessible throughout all the test cases. And once you are done with all the test cases you should release the original methods and clean up the stubs using the method sandbox.
Replaces the spy with the original method. Only available if the spy replaced an existing method. The highlighted sentence is the key. The restore functions in sinon only work on spies and stubs that replace an existing method, and our spy was created as an anonymous (standalone) spy.
The function sinon. spy returns a Spy object, which can be called like a function, but also contains properties with information on any calls made to it. In the example above, the firstCall property has information about the first call, such as firstCall. args which is the list of arguments passed.
The sinon. stub() substitutes the real function and returns a stub object that you can configure using methods like callsFake() . Stubs also have a callCount property that tells you how many times the stub was called. For example, the below code stubs out axios.
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:
According to the docs this behaviour was added in [email protected].
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:
reset
. This keeps the spy. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With