【问题标题】:Dynamically-generated Mocha tests not executing in async/await context动态生成的 Mocha 测试不在异步/等待上下文中执行
【发布时间】:2018-11-23 05:12:27
【问题描述】:

我无法让我的 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() 子句没有执行?

【问题讨论】:

    标签: node.js for-loop mocha.js


    【解决方案1】:

    原来你不能将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.
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2021-10-03
      • 2017-06-15
      • 1970-01-01
      • 2014-05-21
      相关资源
      最近更新 更多