2017-05-25 119 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」從它內部的一個函數動態生成,我想循環並創建下一個測試 –