简体   繁体   English

即使测试没有返回承诺,qunit 如何知道异步测试回调何时完成?

[英]How does the qunit knows when the async test callback is complete even though the tests does not return promise?

Qunit executes the async tests one by one, but how does it know a test is complete, since the tests does not return a Promise which the qunit can await? Qunit 一个一个地执行异步测试,但是它怎么知道测试完成了,因为测试没有返回 qunit 可以等待的 Promise?

In this demo example https://jsfiddle.net/6bnLmyof/在这个演示示例中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 );
});

There are 2 async tests that run one by one.有 2 个异步测试,它们一一运行。 The tests post a macro task (setTimeout) to the event loop, but somehow qunit is able to wait for the test to complete despite the tests not returning promise.测试将宏任务 (setTimeout) 发布到事件循环,但尽管测试未返回承诺,但 qunit 以某种方式能够等待测试完成。 Also, in the souce code of qunit there are no await keywords present.此外,在qunit的源代码中,存在 await 关键字。

Async functions always return Promises which resolve once the end of their block is reached (or a return is reached).异步函数总是返回 Promises,一旦到达它们的块末尾(或到达return值)就会解决。 So even though nothing is explicitly returned, the await s mean that both async callbacks implicitly return Promises that resolve after all await s in the function complete.因此,即使没有明确返回任何内容, await意味着两个异步回调都隐式返回在函数中的所有await完成后解析的承诺。 So test just needs to iterate through each callback function it's called with, and await each call.所以test只需要遍历它调用的每个回调函数,并await每个调用。

Here's an example of how you can implement this yourself too, without changing any of the code inside squareAfter1Second or the test calls:下面是一个示例,说明您也可以自己实现这一点,而无需更改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'); } })();

这就是await的全部意义(异步等待承诺结果,然后才继续)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM