参数
之前我们写 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 是一样的。至于其他的,有兴趣的话可以自己试下。