Qunit逐个执行异步测试,但是它如何知道测试已完成,因为测试未返回qunit可以等待的承诺。
在此演示示例中,https://jsfiddle.net/6bnLmyof/
function squareAfter1Second(x) {
const timeout = x * 1000;
console.log("squareAfter1Second x:", x);
return new Promise(resolve => {
setTimeout(() => {
resolve(x * x);
}, timeout);
});
}
const { test } = QUnit;
test( "an async test", async t => {
console.log("starting test1");
t.equal( await squareAfter1Second(3), 9 );
t.equal( await squareAfter1Second(4), 16 );
});
test( "an async test2", async t => {
console.log("starting test2");
t.equal( await squareAfter1Second(1), 1 );
});
有2个异步测试逐一运行,测试将宏任务(setTimeout)发布到事件循环,但是尽管测试未返回Promise和源代码,但qunit仍能够等待测试完成的qunit没有等待语句。
这是await
的全部内容(异步等待promise结果,并且仅在此之后继续)
异步函数总是返回Promises,一旦到达其块的末尾(或到达return
),它们就会解析。因此,即使未显式返回任何内容,await
也意味着两个异步回调都隐式返回Promises,该Promises将在函数中的所有await
完成后解决。
您也可以自己实现:
const queue = []
const test = (_, callback) => {
queue.push(callback);
};
function squareAfter1Second(x) {
const timeout = x * 1000;
console.log("squareAfter1Second x:", x);
return new Promise(resolve => {
setTimeout(() => {
resolve(x * x);
}, timeout);
});
}
test( "an async test", async t => {
console.log("starting test1");
t.equal( await squareAfter1Second(3), 9 );
t.equal( await squareAfter1Second(4), 16 );
});
test( "an async test2", async t => {
console.log("starting test2");
t.equal( await squareAfter1Second(1), 1 );
});
(async () => {
for (const callback of queue) {
console.log('Awaiting callback...');
await callback({ equal: () => void 0 });
console.log('Callback done');
}
})();