2012-07-06 188 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)); 
      }) 
     }) 
    }) 
})