簡體   English   中英

即使測試沒有返回承諾,qunit 如何知道異步測試回調何時完成?

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

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 以某種方式能夠等待測試完成。 此外,在qunit的源代碼中,存在 await 關鍵字。

異步函數總是返回 Promises,一旦到達它們的塊末尾(或到達return值)就會解決。 因此,即使沒有明確返回任何內容, await意味着兩個異步回調都隱式返回在函數中的所有await完成后解析的承諾。 所以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'); } })();

這就是await的全部意義(異步等待承諾結果,然后才繼續)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM