从零搭建webpack前端类库脚手架[5]-测试你的代码

当你准备开源一个库的时候,一定要写单元测试;当你要使用一个开源库的时候,单元测试的覆盖率是衡量质量的最重要标准之一。

lint

import规范检查

https://github.com/benmosher/eslint-plugin-import#sublimelinter-eslint
之所以要做这个检查,是因为混用不同类型的模块语法,会导致意外的bug。这是官方的一个建议

测试有很多好处

  • 经过了测试的代码至少保证其功能一部分是没问题的
  • 每次增加新功能可以保证不影响到之前的功能
  • 给自己勇气和信心重构代码

单元测试框架

JavaScript社区有2个比较成熟的框架: Jasmine和摩卡(mocha),由于Koa和Express人家都用的mocha,故我这里采用mocha。

基本概念

mocha中有测试suite和test case。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var User = require('./models/user');

describe('models/user', function() {

before(function(done) {
User.new({name: '小明'}, done);
});

after(function(done) {
User.delete({name: '小明'}, done);
})

it('should return an Object when find by name="小明"', function(done) {
User.find({name: '小明'},
function(err, user) {
if (err) {
return done(err);
}
user.should.be.an.Object();
user.name.should.equal('小明');
done();
});
});
});

使用ES6语法编写测试

Mocha 则是一个测试框架,如果需要执行使用ES6语法的测试脚本,可以修改package.json的scripts.test。

“scripts”: {
“test”: “mocha –ui qunit –compilers js:babel-core/register”
}
上面命令中,–compilers参数指定脚本的转码器,规定后缀名为js的文件,都需要使用babel-core/register先转码。

最新版本已经替换为 babel-register 这个单独的库,且废弃了使用–compiler,转而直接全部使用 --require, 且要设置glob类型的测试目录和文件名咯。所以最终是这样:

1
2
3
4
5
"scripts": {
"build": "babel -d lib src",
"test": "npm run build && mocha --require babel-polyfill --require babel-register \"test/*.js\"",
"prepublish": "npm run build"
},

超时设置时,写mocha时不要使用箭头函数,因为箭头函数会改变this指向,导致this无法拿到mocah的上下文。http://mochajs.org/

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context. For example, the following code will fail due to the nature of lambdas:

1
2
3
4
5
6
7
describe('my suite', () => {
it('my test', () => {
// should set the timeout of this test to 1000 ms; instead will fail
this.timeout(1000);
assert.ok(true);
});
});

If you do not need to use Mocha’s context, lambdas should work. However, the result will be more difficult to refactor if the need eventually arises.

异步测试

异步测试需要借助done来告诉mocha何时结束。另外,mocha

Mocha默认每个测试用例最多执行2000毫秒,如果到时没有得到结果,就报错。对于涉及异步操作的测试用例,这个时间往往是不够的,需要用-t或–timeout参数指定超时门槛。

Refer

http://www.ruanyifeng.com/blog/2015/12/a-mocha-tutorial-of-examples.html
https://mp.weixin.qq.com/s?__biz=MzI0MzA3MDQ2OA==&mid=405643683&idx=1&sn=8982a161dffe92560d9bf871272780e6&scene=23&srcid=1229KiUK4zo8r3TI1Fg29Q0S#rd