Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running async code before 'describe' in Mocha [duplicate]

I'm trying to generate tests dynamically using a for-loop, but the number of tests to generate is obtained from a async task. Here is my code:

var noOfTestsToRun;

before(function() {
    return someAsyncTask().then(function(result) {
        noOfTestsToRun = result;
    })
});

describe('My Test Suite', function() {
    for (var i = 0; i < noOfTestsToRun; i++) {
        it('Test ' + i, function() {
            //...
        });
    }
});

However, noOfTestsToRun = result doesn't seem to be executed when it reaches the for loop.

I was wondering if there are any solutions to this kind of problems. Thank you.

like image 929
batluck Avatar asked Oct 29 '22 23:10

batluck


1 Answers

Pass the done callback to your before function.

var noOfTestsToRun;

before(function(done) {
    return someAsyncTask().then(function(result) {
        noOfTestsToRun = result;

        // Complete the async stuff
        done();
    })
});

describe('My Test Suite', function() {
    for (var i = 0; i < noOfTestsToRun; i++) {
        it('Test ' + i, function() {
            //...
        });
    }
});

When your async task is finished and done() is called, we are telling Mocha that the async stuff is finished and it can move on to the expectations.

UPDATE

So, your goal is to have mocha run your dynamic tests.

You can achieve that with a bit of a hack. You will need an it block to force before to execute. And within the before, you can dynamically generate it tests based on your asynchronous result.

before(function() {
    return someAsyncTask().then(function(result) {
        describe('My Test Suite (dynamic)', function() {
            for (var i = 0; i < result; i++) {
                it('Test ' + i, function() {
                    // ...
                });
            }
        });
    });
});

it('should force before to execute', function() {
    console.log('Hack to force before to execute');
});

Working pen

like image 194
Prashant Avatar answered Nov 11 '22 05:11

Prashant