2017-05-25 71 views
0

我正在编写一个代码,其中我的it块生成一个数组,并且我喜欢遍历它并在同一个描述块中执行一些测试。我试图将该数组写入文件并进行访问,但在写入之前,这些测试会先执行。我不能在摩卡测试之外访问a,但我想知道是否有这样做?通过在其中创建的数组循环遍历

it("test",function(done){ 
    a=[1,2,3] 
}) 

a.forEach(function(i){ 
    it("test1",function(done){ 
    console.log(i)  
    }) 
}) 
+0

你想它()在它访问的变量超出范围 – Fahadsk

回答

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

这不工作?

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

()在摩卡框架不起作用 –

0

如何:

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块内吗?

+0

广东话访问“一”之外吧()块,即使在描述声明( ) –

+0

看到我上面的编辑。不幸的是,除非你可以在'it'块之外创建你的数组,否则我认为你被卡住了... –

+0

我有一个测试用例,其中“a”从它内部的一个函数动态生成,我想循环并创建下一个测试 –