【问题标题】:How does the qunit knows when the async test callback is complete even though the tests does not return promise?即使测试没有返回承诺,qunit 如何知道异步测试回调何时完成?
【发布时间】:2023-04-03 16:55:02
【问题描述】:

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 关键字。

【问题讨论】:

    标签: javascript es6-promise qunit


    【解决方案1】:

    Async 函数总是返回 Promises,一旦到达其块的末尾(或到达 return)就会解析。因此,即使没有显式返回任何内容,awaits 也意味着两个异步回调都隐式返回在函数中的所有 awaits 完成后解析的 Promise。所以test 只需要遍历每个调用它的回调函数,以及await 每次调用。

    下面是一个示例,说明您也可以自己实现此功能,而无需更改 squareAfter1Secondtest 调用中的任何代码:

    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');
      }
    })();

    【讨论】:

    • 但是qunit源码code.jquery.com/qunit/qunit-2.9.2.js987654321@中没有await语句
    • await 只是.then 的语法糖,代码确实 有很多.thens(其中44 个)
    • 对。感谢您的示例代码。它如此优雅,它展示了 Qunit 的工作原理。非常令人印象深刻。
    【解决方案2】:

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

    【讨论】:

    • 调用者不必等待被调用者
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2017-05-21
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多