2012-07-06 186 views
10

我想循環一個摩卡測試套件(我想測試我的系統針對無數值與預期的結果),但我無法讓它工作。例如:循環摩卡測試?

規格/ example_spec.coffee

test_values = ["one", "two", "three"] 

for value in test_values 
    describe "TestSuite", -> 
    it "does some test", -> 
     console.log value 
     true.should.be.ok 

的問題是,我的控制檯日誌輸出看起來是這樣的:

three 
three 
three 

,我想它看起來是這樣的:

one 
two 
three 

如何循環這些值爲我的摩卡t EST序列?

回答

12

這裏的問題是你正在關閉「value」變量,所以它總是會評估它的最後一個值。

像這樣的東西會工作:

test_values = ["one", "two", "three"] 
for value in test_values 
    do (value) -> 
    describe "TestSuite", -> 
     it "does some test", -> 
     console.log value 
     true.should.be.ok 

這工作,因爲當值傳遞到這個匿名函數,它被複制到外部函數的新值參數,因此不會被循環改變。

編輯:添加coffeescript「做」的好處。

+1

是的,只是想出了我自己的一個la https://github.com/visionmedia/mocha/issues/420。謝謝! – neezer 2012-07-06 23:36:43

2

您可以使用'數據驅動'。 https://github.com/fluentsoftware/data-driven

var data_driven = require('data-driven'); 
describe('Array', function() { 
    describe('#indexOf()', function(){ 
     data_driven([{value: 0},{value: 5},{value: -2}], function() { 
      it('should return -1 when the value is not present when searching for {value}', function(ctx){ 
       assert.equal(-1, [1,2,3].indexOf(ctx.value)); 
      }) 
     }) 
    }) 
})