gpt4 book ai didi

javascript - 即使返回 promise 后, promise 测试也会超时

转载 作者:行者123 更新时间:2023-12-03 02:31:11 25 4
gpt4 key购买 nike

我研究发现,在 Mocha 中测试 Promise 时,你必须返回 Promise。

我尝试执行以下操作,但测试始终超时。正确的做法是什么?

describe('A promise', () => {

it('should not timeout', () => {

return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hi!');
}, 3000);
}).then((msg) => {
expect(msg).to.equal('hi!');
});

});

});

输出:

$ ./node_modules/mocha/bin/mocha test.js


A promise
1) should not timeout


0 passing (2s)
1 failing

1) A promise
should not timeout:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

编辑:我尝试在 it 行中添加 done 并在我的 then block 中调用它,但是它不起作用

最佳答案

尝试这个(仅更改:“.timeout(5000)”被添加到“it”)。这对我有用。基本上,如果您预计异步调用将花费超过 2 秒,则必须更改异步调用的默认超时 2 秒。

describe('A promise', () => {
it('should not timeout', () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hi!');
}, 3000);
}).then((msg) => {
expect(msg).to.equal('hi!');
});
}).timeout(5000);
});

第二个选项(在这种情况下无需更改测试):

./node_modules/mocha/bin/mocha --timeout 5000 test-mocha-spec.js

关于javascript - 即使返回 promise 后, promise 测试也会超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48726898/

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