gpt4 book ai didi

javascript - 断言失败,因为它不等待 promise 解决

转载 作者:行者123 更新时间:2023-11-30 20:38:16 25 4
gpt4 key购买 nike

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

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

我已经像这样删除了方法

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 失败了,我还看到了更多在“再见”之后打印“你好”。

在 promise resolve 之后测试调用 test 的正确方法是什么?

最佳答案

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

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

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

我会从它的期望中解开你 stub 的方法,可能是这样的:

// in test.js

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

关于javascript - 断言失败,因为它不等待 promise 解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49582157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com