循环执行异步JavaScript(Mocha)

时间:2015-04-22 12:46:29

标签: javascript testing mocha bdd

我正在尝试使用Mocha测试异步JavaScript,并且我在循环填充异步填充的数组时遇到了一些问题。

我的目标是创建N(=arr.length)个测试,每个元素对应一个元素。

可能有一些关于Mocha语义的东西我不知道。

到目前为止,这是我的(非工作)简化代码:

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

我收到的输出是:

  Array test
    ✓ Testing elements


  1 passing (1s)

我希望得到像这样的输出:

  Array test
      Testing elements
      ✓ testing3
      ✓ testing5
      ✓ testing7
      ✓ testing3
      ✓ testing1

  5 passing (1s)

关于如何写这个的任何帮助?

1 个答案:

答案 0 :(得分:2)

我完成这项工作的唯一方法是有点凌乱(因为它需要一个虚拟测试;原因是你不能直接将it()嵌套在另一个it()内,它需要&#34 ;父母&#34;是describe(),您需要it(),因为describe()不支持异步):

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 将在您的输出中结束。

相关问题