遍历在 it 块中创建的数组



我正在编写一个代码,其中我的it块生成一个数组,我喜欢遍历它并在同一个描述块中进行一些测试。我尝试将该数组写入文件并访问它,但是这些测试在我写入它之前先执行。我无法访问a摩卡测试之外的测试,但我想知道是否有办法可以做到这一点?

it("test",function(done){
  a=[1,2,3]
})
a.forEach(function(i){
  it("test1",function(done){
   console.log(i)      
  })
})

这不行吗?

it("test",function(done){
    a=[1,2,3]
    a.forEach(function(i){
        it("test1",function(done){
        console.log(i)
    })
})
var x = [];
describe("hello",function () {
it("hello1",function(done){
    x = [1,2,3];
    describe("hello2",function () {
        x.forEach(function(y) {       
            it("hello2"+y, function (done) {
                console.log("the number is " + y)
                done()
            })
        })
    })
    done()
});
});

怎么样:

describe("My describe", function() {
    let a;
    it("test1", function() {
        a = [1, 2, 3];
    });
    a.forEach(function(i) {
        it("test" + i, function() {
            console.log(i);
        });
    });
});

如果测试是异步的,则需要向其添加done回调。但是对于这个使用console.log()的简单示例,没有必要。

--编辑--

我认为答案是"不,你不能这样做"。我添加了一些console.log语句,看看发生了什么:

describe("My describe", function() {
    let a = [1, 2];
    it("First test", function() {
        console.log('First test');
        a = [1, 2, 3];
    });
    a.forEach(function(i) {
        console.log(`forEach ${i}`);
        it("Dynamic test " + i, function() {
            console.log(`Dynamic test ${i}`);
        });
    });
});

这是输出:

$ mocha
forEach 1
forEach 2

  My describe
First test
    ✓ First test
Dynamic test 1
    ✓ Dynamic test 1
Dynamic test 2
    ✓ Dynamic test 2

  3 passing (7ms)

因此,mocha运行整个describe块并在运行任何it块之前创建动态测试。我不明白在测试开始后,您将如何从it块内部生成更多动态测试。

您的阵列创建是否必须在it块内?

最新更新