动态生成的Mocha测试不在异步/等待上下文中执行

时间:2018-11-15 20:16:50

标签: node.js for-loop mocha

我无法运行我的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()子句未执行?

1 个答案:

答案 0 :(得分:2)

结果是您无法将BroadcastListerner回调传递到async中。谁知道。

因此,为了使所有异步内容正常工作,应按以下步骤进行操作:

describe()