can*_*era 32 javascript unit-testing mocha.js sinon chai
如何在每次测试前重置Sinon间谍的"被叫"计数?
这就是我现在正在做的事情:
beforeEach(function() {
this.spied = sinon.spy(Obj.prototype, 'spiedMethod');
});
afterEach(function() {
Obj.prototype.spiedMethod.restore();
this.spied.reset();
});
Run Code Online (Sandbox Code Playgroud)
但是当我在测试中检查呼叫计数时:
it('calls the method once', function() {
$.publish('event:trigger');
expect(this.spied).to.have.been.calledOnce;
});
Run Code Online (Sandbox Code Playgroud)
...测试失败并报告该方法被调用X次(每次上一次测试也触发同一事件一次).
TJ.*_*TJ. 42
这个问题曾被问过一段时间,但可能仍然很有趣,特别是对于那些刚接触到sinon的人.
this.spied.reset()Obj.prototype.spiedMethod.restore();删除间谍是不需要的.
更新2018-03-22:
正如我在下面的一些评论中指出的那样,stub.reset将做两件事:
根据文档,这个行为是在sinon@2.0.0中添加的.
更新的问题答案是使用stub.resetHistory().
来自文档的示例:
var stub = sinon.stub();
stub.called // false
stub();
stub.called // true
stub.resetHistory();
stub.called // false
Run Code Online (Sandbox Code Playgroud)
更新:
reset.这可以保持间谍.restore.使用sinon时,您可以使用sinon断言进行增强测试.所以不要写expect(this.spied).to.have.been.calledOnce;一个人可以写:
sinon.assert.calledOnce(Obj.prototype.spiedMethod);
Run Code Online (Sandbox Code Playgroud)
这也适用于this.spied:
sinon.assert.calledOnce(this.spied);
Run Code Online (Sandbox Code Playgroud)
还有很多其他的sinon断言方法.旁边calledOnce也有calledTwice,calledWith,neverCalledWith和更大量的兴农的断言.