javascript 重置“被叫”的信浓间谍
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19883505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reset "called" Count on Sinon Spy
提问by cantera
How do I reset the "called" count on a Sinon spy before each test?
如何在每次测试之前重置 Sinon 间谍的“被调用”计数?
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).
...测试失败并报告该方法被调用 X 次(对于也触发相同事件的每个先前测试一次)。
回答by TJ.
This question was asked a while back but may still be interesting, especially for people who are new to sinon.
不久前有人问过这个问题,但可能仍然很有趣,特别是对于不熟悉 sinon 的人。
this.spied.reset()
is not needed as Obj.prototype.spiedMethod.restore();
removes the spy.
this.spied.reset()
不需要,因为Obj.prototype.spiedMethod.restore();
删除了间谍。
Update 2018-03-22:
2018-03-22 更新:
As pointed out in some of the comments below my answer, stub.resetwill do two things:
正如我的回答下面的一些评论所指出的,stub.reset会做两件事:
- Remove the stub behaviour
- Remove the stub history (callCount).
- 删除存根行为
- 删除存根历史记录 (callCount)。
According to the docsthis behaviour was added in [email protected].
根据文档,此行为已添加到 [email protected] 中。
The updated answer to the question would be to use stub.resetHistory().
该问题的更新答案是使用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 spyuse
restore
.
- 如果您只想重置呼叫计数,请使用
reset
. 这留住了间谍。 - 要删除间谍,请使用
restore
.
When working with sinon you can use the sinon assertionsfor enhanced testing. So instead of writing expect(this.spied).to.have.been.calledOnce;
one could write:
使用 sinon 时,您可以使用sinon 断言进行增强测试。所以不是写expect(this.spied).to.have.been.calledOnce;
一个可以写:
sinon.assert.calledOnce(Obj.prototype.spiedMethod);
This would work as well with this.spied
:
这也适用于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.
还有很多其他的 sinon 断言方法。旁边calledOnce
也有calledTwice
,calledWith
,neverCalledWith
和更大量的兴农的断言。