gpt4 book ai didi

async-await - mocha async/await 测试因超时而失败

转载 作者:行者123 更新时间:2023-12-03 22:43:59 37 4
gpt4 key购买 nike

我想用 Mocha 测试异步代码.

我跟着这个教程testing-promises-with-mocha .最后,它说最好的方法是 async/await。

以下是我的代码,我打算将 setTimeout 设置为比 Mocha 默认值更长的时间。

describe('features', () => {
it('assertion success', async() => {
const resolvingPromise = new Promise( resolve => {
setTimeout(() => {
resolve('promise resolved')
}, 3000)
})

const result = await resolvingPromise
expect(result).to.equal('promise resolved')
})
})

Mocha 给我的错误如下:
Error: Timeout of 2000ms exceeded. For async tests and hooks, 
ensure "done()" is called; if returning a Promise, ensure it resolves...

如何解决错误?简单套装 mocha --timeout 10000更长?

谢谢你的时间!
Mocha: 5.2.0
Chai: 4.2.0

最佳答案

对于异步测试,您应该调用 done()打回来。

describe('features', () => {
it('assertion success', async(done) => { // pass done here
const resolvingPromise = new Promise( resolve => {
setTimeout(() => {
resolve('promise resolved')
}, 3000)
})

const result = await resolvingPromise
expect(result).to.equal('promise resolved')
done() // invoke at end
})
})

关于async-await - mocha async/await 测试因超时而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953389/

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