首页 > 解决方案 > Mocha selenium web 测试中的嵌套 forEach 失败

问题描述

我正在编写一个应该执行以下操作的测试脚本(这是一个示例,但逻辑和结构是相同的)。

调用包含在 its() 中,因为如果数组中的一个元素失败,那么它需要优雅地失败并继续处理数组中的下一个元素。

对此的预期结果应该是:

1 10 20 30 2 10 20 30 3 10 20 30

相反,我收到 1 2 3

这让我相信初始函数是异步调用的。

var arr1 = [1,2,3]
var arr2 = [10,20,30]

function arr_func_1(item){
    console.log(item);

    arr2.forEach(function(item){
        it('should loop through arr2, function(){
            arr_func_2(item);
        })
    });
}

function arr_func_2(item){
    console.log(item);
}

describe('test case', function(){
    arr1.forEach(function(item){
         it('should loop through array 1', function(){   
              arr_func_1(item);
         })
    }
})

标签: node.jsasynchronousmocha.jsdescribe

解决方案


Tests should be defined before they run. should loop through arr2 tests are defined when should loop through array 1 is running, so they are ignored during test run.

Apart from the loops, this is similar to:

describe('test case', function(){
     it('should loop through array 1', function(){   
         it('should loop through arr2, function(){})
     })
})

it block shouldn't be defined inside another it.

It possibly needs to be:

describe('test case', function(){
  for (const item1 of arr1) {
    it('should loop through array 1', function(){...});

    for (const item2 of arr2) {
      it('should loop through array 2', function(){...});
    }
  }
});

推荐阅读