Qunit 一个接一个地执行异步测试,但它如何知道测试已完成,因为测试不会返回 qunit 可以等待的 Promise?
在此演示示例中 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) 发布到事件循环,但不知何故 qunit 能够等待测试完成,尽管测试没有返回 promise。此外,在 qunit 的源代码中没有 await 关键字。
最佳答案
异步函数总是返回一旦到达其 block 末尾(或到达return
)就解决的Promises。因此,即使没有显式返回任何内容,await
也意味着两个异步回调都隐式返回在函数中的所有 await
完成后解析的 Promises。所以 test
只需要遍历调用它的每个回调函数,并 await
每次调用。
下面是一个您也可以自己实现的示例,无需更改 squareAfter1Second
或 test
调用中的任何代码:
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');
}
})();
关于javascript - 即使测试没有返回 promise,qunit 如何知道异步测试回调何时完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59318831/