我有异步测试,其中 spy 在一个测试中启动,下一个测试运行,而 spy 仍包含在第一个测试中。这意味着 assert(spy.usedOnce)
失败。它被调用了两次;assert(spy.usedTwice)
通过了,但是错误地; 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
})
})
单独的描述 block 不能解决问题。
最佳答案
这是由于缺少 return
语句造成的。现在,这些 block 会等待正确的时间执行。添加 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
})
})
关于javascript - 如何在异步测试中对 sinon spy 进行计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899490/