【问题标题】:Assertion fails as it does not wait for promise resolution断言失败,因为它不等待承诺解决
【发布时间】:2018-09-09 22:50:09
【问题描述】:

我使用 mocha、sinon 和 chai 运行一组测试。这是我正在测试的方法

fn.method().then(function(response) {
  console.log(response)
  test()
})

我已经像这样删除了method

test = sinon.spy()  
fn = { method: sinon.stub().resolves("hello") }

在我的测试中我有

expect(fn.method()).to.have.been.called
console.log("goodbye")
expect(test).to.have.been.called

我希望测试通过并按顺序打印“hello”和“goodbye”,但我看到expect(test).to.have.been.called 失败,而且我看到“hello”在“goodbye”之后打印。

在 promise 解决后测试 test 是否被调用的正确方法是什么?

【问题讨论】:

标签: javascript unit-testing promise sinon stub


【解决方案1】:

它失败了,因为(大概)在 sinon .resolves 钩子中有足够的异步性,你的两行

console.log("goodbye");
expect(test).to.have.been.called;

在测试方法的.then 块内的代码运行之前运行。 (我们知道它正在运行,因为我们看到控制台正在记录,但我们知道它必须在第二个 expect 行之后运行。)

我会从预期中解开你的存根方法,可能是这样的:

// in test.js

fn.method().then(() => {
  expect(test).to.have.been.called;
});

【讨论】:

  • 啊。我以为我试过这个但它不起作用(它抛出了一个then is undefined 错误)但我正在做fn.method.then() 而不是fn.method().then()。哦。谢谢!
猜你喜欢
  • 2019-04-29
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2017-04-04
相关资源
最近更新 更多