通过异步JavaScript(Mocha)循环进行测试 [英] Tests from looping through async JavaScript (Mocha)

查看:145
本文介绍了通过异步JavaScript(Mocha)循环进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Mocha测试异步JavaScript,并且在遍历异步填充的数组时遇到一些问题.

I'm trying to test asynchronous JavaScript with Mocha, and I have some issues with looping through an asynchronously filled array.

我的目标是创建N(=arr.length)个测试,为数组的每个元素创建一个.

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

我可能缺少有关Mocha语义的一些东西.

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

我收到的输出是:

  Array test
    ✓ Testing elements


  1 passing (1s)

我想要这样的输出:

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

  5 passing (1s)

对如何编写此内容有帮助吗?

Any help on how to write this?

推荐答案

我完成这项工作的唯一方法是有些混乱(因为它需要一个虚拟测试;原因是您不能将it()直接嵌套在另一个内部it(),它要求父级"是describe(),并且您需要一个it(),因为describe()不支持异步):

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

});

dummy 将会最终出现在您的输出中.

The dummy will end up in your output.

这篇关于通过异步JavaScript(Mocha)循环进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆