即使测试未返回promise,qunit如何知道异步测试回调何时完成?

问题描述 投票:0回答:2

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没有等待语句。

javascript es6-promise qunit
2个回答
0
投票

这是await的全部内容(异步等待promise结果,并且仅在此之后继续)


0
投票

异步函数总是返回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');
  }
})();
© www.soinside.com 2019 - 2024. All rights reserved.