Tests related to the asynchronous JavaScript loop (Mocha)

I am trying to test asynchronous JavaScript with Mocha, and I have some problems with looping through an asynchronously populated array.

My goal is to create N ( =arr.length) tests , one for each element of the array.

Probably something about the semantics of Mocha is missing.

This is my (non-working) simplified code:

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 result obtained:

  Array test
     Testing elements


  1 passing (1s)

I would like to have a conclusion like this:

  Array test
      Testing elements
       testing3
       testing5
       testing7
       testing3
       testing1

  5 passing (1s)

Any help on how to write this down?

+4
source share
1 answer

, , ( , , it() it(), , describe(), it(), describe() 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();
  });

});

dummy .

+2

Source: https://habr.com/ru/post/1584022/


All Articles