2013-07-10 94 views
13

如何使用Mocha創建參數化測試?Mocha參數化測試

示例用例:我有10個類,即10個不同的相同接口的實現。我想爲每個班級運行完全相同的測試。我可以創建一個函數,將類作爲參數並運行該類的所有測試,但隨後我將在一個函數中進行所有測試 - 我將無法將它們很好地分隔到不同的「describe」子句。 ..

在摩卡有沒有一種自然的方式來做到這一點?

+2

這裏是不使用異步http://stackoverflow.com/questions/18166770/mocha-js-how-to-reuse-assertions-within-a-spec – artkoshelev

回答

9

看看async.each。它應該使您能夠調用相同的describe,it和expect/should語句,並且可以將參數傳遞給閉包。

var async = require('async') 
var expect = require('expect.js') 

async.each([1,2,3], function(itemNumber, callback) { 
    describe('Test # ' + itemNumber, function() { 
    it("should be a number", function (done) { 
     expect(itemNumber).to.be.a('number') 
     expect(itemNumber).to.be(itemNumber) 
     done() 
    }); 
    }); 
callback() 
}); 

給我:

$ mocha test.js -R spec 
    Test # 1 
    ✓ should be a number 
    Test # 2 
    ✓ should be a number 
    Test # 3 
    ✓ should be a number 
    3 tests complete (19 ms) 

下面是一個更復雜的例子結合async.series和async.parallel:Node.js Mocha async test doesn't return from callbacks

+6

一個很好的例子是真的有必要使用異步,不會array.every(foreach循環)做同樣的事情,而不需要另一個第三方工具? – Dukeatcoding

+0

'async'是一個很棒的lib,我在Node.js-land中很喜歡,但是包裝Mocha用異步調用描述塊是Mocha的不正確用法。首先,應始終在事件循環的下一個記號中始終調用異步庫中的回調。其次,Mocha同步註冊所有塊和掛鉤 - 如果您異步註冊塊,則不能保證它會運行。查看摩卡的延遲功能:https://github.com/mochajs/mocha/issues/362 –

20

你不需要async包。你可以直接使用forEach循環:

[1,2,3].forEach(function (itemNumber) { 
    describe("Test # " + itemNumber, function() { 
     it("should be a number", function (done) { 
      expect(itemNumber).to.be.a('number') 
      expect(itemNumber).to.be(itemNumber) 
     }); 
    }); 
}); 
+1

用'[1,4] .forEach(function(itemNumber){'我得到了'TypeError:無法調用方法'forEach' 'undefined' – hellboy

+0

我應該總是用'array'代替'dictionary'嗎? – hellboy

+0

@hellboy你可以分享代碼片段嗎? –

5

我知道這是前一段時間發佈的,但現在有一個節點模塊,這使得這非常簡單! mocha param

const itParam = require('mocha-param').itParam; 
const myData = [{ name: 'rob', age: 23 }, { name: 'sally', age: 29 }]; 

describe('test with array of data',() => { 
    itParam("test each person object in the array", myData, (person) => { 
    expect(person.age).to.be.greaterThan(20); 
    }) 
})