原文:http://visionmedia.github.io/mocha/
assert、should等断言库,一旦出现测试失败,整个程序都会退出。所以要使用测试框架,比如mocha。
mocha并不直接参与测试,它主要管理测试用例,生成各种类型的报告。它可以使用should作为断言库。mocha还提供了更方便的测试异步调用的语法,提供了更易用的超时设置等。
在项目构建工具Grunt中,提供了grunt-mocha-test插件,其实就是mocha,还提供了grunt-blanket,可以提供覆盖率测试。
安装
$ npm install -g mocha
(使用grunt的插件grunt-mocha-tes,安装不同)
测试同步调用
mocha测试同步调用的代码时,逐一测试每个断言
describe('Array', function(){ //describe就相当于对断言进行分类、形成目录型结构
describe('#indexOf()', function(){ //分类下还可以再分类
//it后包含真正的断言
it('should return -1 when the value is not present', function(){
[1,2,3].indexOf(5).should.equal(-1);
[1,2,3].indexOf(0).should.equal(-1);
})
})
})
测试异步调用
异步调用的测试分成两部分:
1,确定该调用确实被执行了;2,期望的断言成功;
it( 'fs.readFile should be ok',function(){
fs.readFile('./package.json','utf-8',function(err,data){
should.not.exist(err);
done();
})
});
it('respond with matching records', function(done){
db.find({ type: 'User' }, function(err, res){
if (err) return done(err); //2
res.should.have.length(3); //1
done(); //2
})
})
设置测试用例执行前、后环境
mocha提供before()
, after()
, beforeEach()
, afterEach()等方法,用于设置测试用例执行前、后的环境
\\在‘connection’这个段落里,所有的用例在执行之前,都会执行下面的代码,它设置了数据库为空,这很有用。
\\它放在哪个级别的describe里面,则那个段落里面所有用例都会应用它。如果把它放在所有的describe之上,那所有的用例都应用它。 beforeEach(function(done){
db.clear(function(err){
if (err) return done(err);
db.save([tobi, loki, jane], done);
});
})
describe('#find()', function(){
it('respond with matching records', function(done){
db.find({ type: 'User' }, function(err, res){
if (err) return done(err);
res.should.have.length(3);
done();
})
})
})
})
.only
整篇测试用例中,只测试.only的用例。只想看某测试用例结果时。
describe('Array', function(){ describe.only('#indexOf()', function(){ //只有这个describe下的测试用例会跑起来
...
})
})
或者在it下
describe('Array', function(){
describe('#indexOf()', function(){
//只有这个it下的测试用例会执行,整篇js文件的其他用例都暂时搁置了。 it.only('should return -1 unless present', function(){
})
it('should return the index when present', function(){
})
})
})
.skip
和.only正好相反,设置了.skip的describe或者it当前不去执行。
大多数的mocha测试报告会提示每个describe花费的时间,如下spec格式的报告
显示期望值和实际值的对比
mocha的报告可以显示测试实际得到的值,同时显示期望的值,我们可以方便的看到他们的区别。
或者是:
Suite specific timeouts
设置超时
可以使用this.timeout(毫秒数)设置describe级别、it级别的超时。该设置会被更低级别的this.timeout(毫秒数)设置所覆盖.
describe('a suite of tests', function(){
this.timeout(500);
it('should take less than 900ms', function(done){
this.timeout(900);
setTimeout(done, 300);
})
it('should take less than 500ms as well', function(done){
setTimeout(done, 200);
})
})