代码之家  ›  专栏  ›  技术社区  ›  montrealist

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

  •  0
  • montrealist  · 技术社区  · 6 年前

    getStatus()

    )你可以玩它 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 回复  |  直到 6 年前
        1
  •  3
  •   montrealist    6 年前

    结果是你不能通过考试 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.
            });
        }
    });