I'm trying to test asynchronous JavaScript with Mocha, and I have some issues with looping through an asynchronously filled array.
My goal is to create N (=arr.length
) tests, one for each element of the array.
Probably there's something about Mocha semantics I'm missing.
This is my (non working) simplified code so far:
var arr = []
describe("Array test", function(){
before(function(done){
setTimeout(function(){
for(var i = 0; i < 5; i++){
arr.push(Math.floor(Math.random() * 10))
}
done();
}, 1000);
});
it('Testing elements', function(){
async.each(arr, function(el, cb){
it("testing" + el, function(done){
expect(el).to.be.a('number');
done()
})
cb()
})
})
});
The output I receive is:
Array test
✓ Testing elements
1 passing (1s)
I'd like to have an output like this one:
Array test
Testing elements
✓ testing3
✓ testing5
✓ testing7
✓ testing3
✓ testing1
5 passing (1s)
Any help on how to write this?
The only way I got this working is a bit messy (because it requires a dummy test; the reason is that you cannot directly nest an it()
inside another it()
, it requires the "parent" to be a describe()
, and you need an it()
because describe()
doesn't support async):
var expect = require('chai').expect;
var arr = [];
describe('Array test', function() {
before(function(done){
setTimeout(function(){
for (var i = 0; i < 5; i++){
arr.push(Math.floor(Math.random() * 10));
}
done();
}, 1000);
});
it('dummy', function(done) {
describe('Testing elements', function() {
arr.forEach(function(el) {
it('testing' + el, function(done) {
expect(el).to.be.a('number');
done();
});
});
});
done();
});
});
The dummy
will end up in your output.
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