一. 单元测试
单元测试分为两种:
TDD:Test-Driven Development,测试驱动开发,注重输出结果。
BDD:Behavior Driven Development,行为驱动开发,注重测试逻辑。
对于TDD、BDD的区别可查看: 关于TDD、BDD和DDD的一些看法 。
对于单元测试,推荐查看 【译】每个单元测试必须回答的 5 个问题 。
mocha默认的模式是BDD。
二. Mocha介绍
在Node.js中,目前比较流行的单元测试组合是 mocha + chai 。mocha是一个测试框架,chai是一个断言库,所以合称”抹茶”。
断言库类型有: jasmine 、 should.js 、 chai 、 assert 。哪个更好主要看团队和项目需要吧,个人喜欢chai断言库的assert风格,更接近原生也更人性化。
Mocha主要特性有:
支持异步的测似用例,如Promise;
支持代码覆盖率coverage测试报告;
支持配置不同的测试(如断言库);
… …
本文使用的是: Mocha + chai(assert风格) 。
安装如下:
npm install mocha -g
npm install mocha
npm install chai
跑Mocha测试的命令:
mocha [debug] [options] [files]
如:
mocha --recursive test/
三. Mocha的三个基本方法:
Mocha有三个基本方法:
describe(moduleName, function)
describe是可嵌套的,描述测试用例是否正确。
describe(‘测试模块的描述’, function() {
// …
});
it(info, function)
info为描述性说明。一个it对应一个单元测试用例。
describe(‘单元测试的描述,一般写明用途和返回值’, function() {
// …
});
assert.equal(exp1, exp2)
mocha的断言语句,判断exp1是否等于exp2。
四. Mocha的异步代码测试:
done
一个it里面只有一个done。
done标识回调的最深处,也是嵌套回调函数的末端。
备注:在mocha v3.x版本,Promise回调不需要使用 done 来标识回调最深处,并且在Promise回调中是用done回报错。
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(done);
});
});
});
五. Test Hooks方法:
before() 、 after() 、 beforeEach() 、 afterEach() 是基于BDD风格提出的。用于预处理和test后的处理。
Test Hooks方法的几个注意点:
beforeEach会对当前describe下的所有子case生效;
before和after的代码没有特殊顺序要求;
同一个describe下的执行顺序为before、beforeEach、afterEach、after;
当一个it有多个before的时候,执行顺序是从最外围的describe的before开始,其他同理。
describe('hooks', function() {
before(function() {
// runs before all tests in this block
});
after(function() {
// runs after all tests in this block
});
beforeEach(function() {
// runs before each test in this block
});
afterEach(function() {
// runs after each test in this block
});
// test cases
});
Hooks的三种写法:
beforeEach(function() {
});
beforeEach(function nameFun() {
});
beforeEach(“some description”, function() {
});
http://www.51testing.com/html/08/n-3715208.html