我研究了,发现在摩卡的测试承诺时,您必须退还承诺。
我尝试执行以下操作,但是测试会保持时间表。什么正确的方法?
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.
edit :我尝试在it
行中添加done
并在我的then
块中调用,但它不起作用
尝试此(仅更改:" .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
此起作用吗?
it('should not timeout', done => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('hi!');
}, 1000);
}).then((msg) => {
expect(msg).to.equal('hi!');
done();
});
});
首先,您需要在回调中添加完成的参数
it('should not timeout', (done) => {
并在最后称呼它,
}).then((msg) => {
expect(msg).to.equal('hi!');
done()
});
您有3个选项:
- 返回诺言
- 使用完成(如果您还返回承诺错误扔(
- 使用异步/等待
在所有这些情况下,您都必须设置超时阈值,因为摩卡咖啡无法确定您是否可以解决异步电话。这是防止无尽测试的保护。
通常,您需要伪造承诺的电话,并以某些假价值立即解决承诺,因此您不会遇到此类问题。