javascript - 如何在异步测试中对 sinon spy 进行计时

标签 javascript mocha.js sinon

我有异步测试,其中 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/

相关文章:

javascript - 自定义图标字体未显示在我的网站上但显示给其他人?

node.js - 带promise的node/vue.js单元测试,如何正确编写?

node.js - 如何测试 stub 数据库查询

javascript - 使用 Jasmin 和 Sinon 对 Backbone 类构造函数进行 stub

javascript - 如何使用 jQuery 将文本添加到特定的 div 元素?

javascript - 改进当前的递归函数?

javascript - Chartjs实时图形x轴移动

node.js - 如何使用 mocha 测试我的 express 应用程序?

node.js - Mongoose 模型测试需要模型

javascript - Sinon spy 期望嵌套函数中的函数调用