Javascript 重置";称为;指望西农间谍

Javascript 重置";称为;指望西农间谍,javascript,unit-testing,mocha.js,sinon,chai,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(); }); 但当我在测试中检查呼叫计数时: it('calls the method on

如何在每次测试前重置Sinon间谍的“被叫”计数

以下是我现在正在做的:

beforeEach(function() {
  this.spied = sinon.spy(Obj.prototype, 'spiedMethod');
});

afterEach(function() {
  Obj.prototype.spiedMethod.restore();
  this.spied.reset();
});
但当我在测试中检查呼叫计数时:

it('calls the method once', function() {
  $.publish('event:trigger');
  expect(this.spied).to.have.been.calledOnce;
});

…该测试失败,并报告称该方法被调用了X次(之前的每个测试都会触发同一事件,每次调用一次)。

这个问题在不久前被问到,但可能仍然很有趣,特别是对于新加入sinon的人来说

this.spied.reset()
不需要作为
Obj.prototype.spiedMethod.restore()删除间谍

更新2018-03-22

正如我在下面的一些评论中指出的,我的回答将做两件事:

  • 移除存根
  • 删除存根历史记录(callCount)
  • 根据调查,这种行为被添加到sinon@2.0.0.

    问题的最新答案是使用

    文档中的示例:

    var stub = sinon.stub();
    
    stub.called // false
    
    stub();
    
    stub.called // true
    
    stub.resetHistory();
    
    stub.called // false
    
    更新:

    • 如果您只想重置呼叫计数,请使用
      重置
      。这让间谍留下来了
    • 删除间谍请使用
      还原
    使用sinon时,您可以使用进行增强测试。因此,不要编写
    expect(this.spied).to.have.been.calledOnce一个人可以写:

    sinon.assert.calledOnce(Obj.prototype.spiedMethod);
    
    这也适用于
    此。spied

    sinon.assert.calledOnce(this.spied);
    

    还有很多其他sinon断言方法。除了被调用的
    之外,还有
    被调用的wice
    被调用的
    从不被调用的
    ,还有很多其他功能。

    spiedObject.reset()对我很有用。问题可能是因为您进行了还原?
    spiedObject.reset()
    似乎是一种更干净的方法。@dman既然您提到了它,我重新阅读了这个问题,重置呼叫计数
    reset
    是正确的,因为您可能希望保留间谍。警告(?):有副作用。使用
    stub.reset()
    重置时,它还会重置
    .returns()
    。我希望保留回执,只重置通话次数。编辑:使用
    stub.resetHistory()
    仅重置计数器
    stub.reset()
    同时删除
    stub.callsFake((args)=>{…})
    因此
    stub.resetHistory()
    似乎是只删除调用计数的更好选项我确信
    spy.reset()
    方法现在已被弃用。如果要重置spy的状态,
    spy.resetHistory()
    spy.reset()
    更好。