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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With