Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tests from looping through async JavaScript (Mocha)

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?

like image 793
Lorenzo Marcon Avatar asked Nov 01 '22 06:11

Lorenzo Marcon


1 Answers

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.

like image 74
robertklep Avatar answered Nov 12 '22 17:11

robertklep