參數
之前我們寫 Mocha測試用例的時候,主要用 describe(), it() 組織用例。這跟 Jasmine 風格是類似的。實際上,這隻是 Mocha 支援的一種而已。
在指令行中,有如下指令可供我們選擇。
-u, --ui <name> specify user-interface (bdd|tdd|qunit|exports)
預設情況下,Mocha使用 bdd 幫我們執行 describe(), it() 的用例。
describe('#indexOf()', function(){
it('should return -1 when not present', function(){
[1,2,3].indexOf(4).should.equal(-1);
});
});
我們也可以選擇其他接口類型。比如 tdd。
Mocha的測試接口類型指的是集中測試用例組織模式的選擇,更像是為使用者提供幾種組織測試用例的方式。
BDD
BDD行為驅動開發,全名 Behavior Driven Development。
Mocha預設的測試接口。 BDD測試接口提供 describe(), context(), it(), specify(), before(), after(), beforeEach(), 和 afterEach()幾種函數,其中context函數隻是describe函數的别名,specify函數也是it函數的别名。
另外,Jasmine的測試風格就是bdd,它的特征就是使用describe,it。 對 BDD 有興趣的可以去這個網站看下
http://jbehave.org/introduction.html
TDD
TDD,測試驅動開發(Test-Driven Development)
TDD接口提供 suite(), test(), suiteSetup(), suiteTeardown(), setup(), 和 teardown()函數,用例寫法如下:
suite('#indexOf()', function(){
test('should return -1 when not present', function(){
([1,2,3].indexOf(4)).should.be.eql(-1);
});
});
tdd跟bdd差別在于,它使用suite,test,suiteSetup,suiteTeardown,setup,teardown 等函數。
Exports
exports 跟 node 裡的子產品文法很像,before, after, beforeEach, and afterEach 都是作為對象的屬性,其它對象的值預設是 suite,屬性是函數的話,代表是一個test。簡單來說,除了鈎子函數,對象是 測試集, 屬性是 測試用例。
require("should");
module.exports = {
before: function(){
// ...
},
'Array': {
'#indexOf()': {
'should return -1 when not present': function(){
[1,2,3].indexOf(4).should.equal(-1);
}
}
}
};
鈎子函數
從 BDD 到 TDD,describe 和 it 變變成了 suite, test。對應的鈎子函數也變了。那它們的行為有沒有改變呢?下面是個例子。
var assert = require('assert');
var mocha = require('mocha');
require("should");
suite('Array', function(){
suiteSetup(function(){
console.log();
console.log('-----------suiteSetup');
});
suiteTeardown(function(){
console.log('-----------suiteTeardown');
console.log();
});
setup(function(){
console.log();
console.log('-----------setup');
});
teardown(function(){
console.log('-----------teardown');
console.log();
});
test('First layer', function(){
([1,2,3].indexOf(4)).should.eql(-1);
});
suite('Second layer', function(){
suiteSetup(function(){
console.log();
console.log('-----------Second layer suiteSetup');
});
setup(function(){
console.log();
console.log('-----------Second layer setup');
});
test('Second layer test', function(){
([1,2,3].indexOf(4)).should.eql(-1);
});
});
});
輸出

從上面可以看出,每個内層測試用例執行前會執行外層的 setup, 這點跟 bdd 是一樣的。至于其他的,有興趣的話可以自己試下。