如何在异步测试中为 sinon 间谍计时

How to time sinon spies across async tests

我有异步测试,其中一个间谍在一个测试中启动,下一个测试运行,而间谍仍然包裹在第一个测试中。这意味着 assert(spy.calledOnce) 失败了。它被调用了两次;assert(spy.calledTwice) 错误地通过了; restore() 没有被及时调用。

myControler.aMethod 内部调用了间谍方法 myModule.myMethod 我怎样才能解决这个问题?

it('test one', function() {
  sinon.spy(myModule, 'myMethod')
  myControler.aMethod().then(res => {
    // second test runs before this is called and calls it a second time
    assert(myModule.myMethod.calledOnce)    
    teamController.getAllTeamSlugs.restore()
  })
})
it('test two', function() {
  const fakeCache = {}
  // this runs before the above test can restore the spy
  myControler.aMethod().then(res => {
   // some asserts
  })
})

单独描述块不能解决问题。

这是由于缺少 return 语句造成的。这些块现在等到正确的时间执行。添加 returns 使工作代码如下:

it('test one', function() {
  sinon.spy(myModule, 'myMethod')
  return myControler.aMethod().then(res => {
    // second test runs before this is called and calls it a second time
    assert(myModule.myMethod.calledOnce)    
    teamController.getAllTeamSlugs.restore()
  })
})
it('test two', function() {
  const fakeCache = {}
  // this runs before the above test can restore the spy
  return myControler.aMethod().then(res => {
   // some asserts
  })
})