12

我正在尝试循环 mocha 测试套件(我想针对无数具有预期结果的值测试我的系统),但我无法让它工作。例如:

规格/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

如何为我的 mocha 测试循环这些值?

4

2 回答 2

13

这里的问题是您正在关闭“值”变量,因此它将始终评估为其最后一个值。

像这样的东西会起作用:

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

这是有效的,因为当值被传递到这个匿名函数时,它被复制到外部函数中的新值参数,因此不会被循环更改。

编辑:添加了咖啡脚本“做”的好处。

于 2012-07-06T23:35:54.163 回答
3

您可以使用“数据驱动”。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));
            })
        })
    })
})
于 2015-07-14T20:27:58.453 回答