Mocha testing inside async callbacks

前端 未结 1 1245
-上瘾入骨i
-上瘾入骨i 2021-01-27 00:37

I have simplified the example to be able to explain it well. I have an array which I want to iterate on. For each element of the array I want to execute a test with async/await

1条回答
  •  一生所求
    2021-01-27 01:08

    Mocha does not support asynchronous describe functions. You can generate tests dynamically, as described here, but that generation must still be synchronous.

    Any tests that aren't created synchronously won't be picked up by the runner. Hence the 0 passing line at the top of your output. Mocha has decided there are no tests well before your promise resolves.

    This isn't to say testing your stuff is impossible, just that you need to rethink how you're using Mocha to test it. The following, for example, would be similar to loading all of your things up front and making an assertion on each one in various tests:

    const chai = require('chai');
    const expect = chai.expect;
    
    describe('Each item', () => {
        let items;
    
        before(async () => {
            items = [];
            await Promise.all([1, 2, 3].map(async(n) => {
                await new Promise(resolve => setTimeout(() => resolve(), 1000));
                items.push(n);
            }));
        })
    
        it('is a number', () => {
            for (item of items) {
                expect(item).to.be.a('number');
            }
        });
    
        it('is an integer', () => {
            for (item of items) {
                expect(item % 1).to.equal(0)
            }
        });
    
        it('is between 1 and 3', () => {
            for (item of items) {
                expect(item).to.be.within(1, 3)
            }
        });
    });
    

    Unfortunately you won't be able to make a fully separate test displaying in your output for each item. If you want this, you may check out another test runner. I don't really have enough experience with others to say whether or not any of them support this. I'd be surprised if they do, though, since it's quite unusual.

    0 讨论(0)
提交回复
热议问题