【问题标题】:Mocha tests for expressjs 4, spying on a function called in a promise, tests fail silentlymocha 测试 expressjs 4,监视一个在 promise 中调用的函数,测试静默失败
【发布时间】:2014-10-06 02:30:03
【问题描述】:

我有一些看起来像这样的测试:

it('does stuff', function(done) {
  somePromise.then(function () {
    expect(someSpy).to.have.been.called
    done()
  })
})

如果该测试中的断言失败,它将静默失败,并且测试本身将超时,因为永远无法达到done()。例如,这个:

it('does stuff', function(done) {
  expect(1).to.equal(2)

  somePromise.then(function () {
    expect(someSpy).to.have.been.called
    done()
  })
})

将失败并出现一个很好的错误,说明我们期待 1 但得到 2。但是,这个:

it('does stuff', function(done) {
  somePromise.then(function () {
    expect(1).to.equal(2)

    expect(someSpy).to.have.been.called
    done()
  })
})

将因超时而失败。我认为问题是我不在“它”上下文中,但处理这个问题的最佳方法是什么?

【问题讨论】:

  • 当您将done() 移动到.then() 的最后一个或外部和第一个时会发生什么?
  • 如果done()then() 之外,则测试将在promise 解析和断言执行之前完成。

标签: javascript node.js express promise mocha.js


【解决方案1】:

失败的断言基本上是抛出的错误。你可以catch他们,就像你可以处理 Promise 中的任何错误一样。

it('does stuff', function(done) {
  somePromise.then(function () {
    expect(1).to.equal(2)

    expect(someSpy).to.have.been.called
    done()
  })
  .catch(done)
})

【讨论】:

  • 就是这样。我正在使用猫鼬承诺,所以我必须使用.onReject(errFunc),但这回答了问题。
猜你喜欢
  • 2021-04-24
  • 2016-05-26
  • 2017-04-08
  • 2015-08-04
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多