动态生成的 Mocha 测试未在 async/await 上下文中执行

Dynamically-generated Mocha tests not executing in async/await context

我无法将我的 Mocha 测试设为 运行。我需要测试的部分内容是我以异步方式(从远程服务器)获取,由我的 getStatus() 函数返回(为简单起见用超时替换)。我有一个没有 async/await 的类似代码示例,它工作正常(如果需要,也可以提供 repl.it)。

精简代码(可以玩玩here on repl.it):

const sleep = require('util').promisify(setTimeout);

const getStatus = async function() {
    await sleep(1000);
    return 2;
};

describe('main describe', async function () {
    let uids = [1,2,3];

    describe('Tha test!', async function () {
        console.info('started describe() block...');

        let outcome;
        let status;

        const callback = function () {
            console.info(`inside callback, status is ${status} and outcome is ${outcome}`);
            expect(status).to.equal(outcome);
        };

        for(let uid in uids) {
            status = await getStatus(uids[uid]);
            console.info('the status returned by getStatus is:', status);
            it(`The status for ${uids[uid]} should be ${outcome}`, callback);
        }
    });
});

注意:it() 子句中的回调灵感来自 this question.

输出:

started describe() block...

  0 passing (0ms)

the status returned by getStatus is: 2
the status returned by getStatus is: 2
the status returned by getStatus is: 2

预期输出:

started describe() block...

the status returned by getStatus is: 2
the status returned by getStatus is: 2
the status returned by getStatus is: 2

      1) number 0 should equal 2
      2) number 1 should equal 2
      ✓ number 2 should equal 2

  1 passing (11ms)
  2 failing

问题:为什么我的 it() 子句没有执行?

原来你不能将 async 回调传递给 describe()。谁知道呢

因此,为了使所有异步内容正常工作,应该如何完成:

describe('do not put async before the function keyword!', function () {
    uids = process.env.ENV_OBJECTS.split(',');

    let outcome;

    for(let uid in uids) {
        it('Can safely put async before the function here', async function() {
            outcome = await getOutcome(uid);
            // etc.
        });
    }
});