公司最近牵起一片Unit Test热,为了迎合公司的口味,我也只能把unit test(其实我写的不是UT,算是integration/aaceptance test了)加入其中。目前来讲,nodeJs的ut框架,最有名的应该是TJ大神的mocha了 (有很详细的官方文档:http://visionmedia.github.io/mocha/)。废话少说,切入正题:javascript
1、安装:mocha是要求全局安装的,那么: npm install -g mochahtml
2、组织目录结构:java
我建立了一个子目录test,用来存放全部的test case,mocha默认会测试./test/*.js。同时我也建立了2个bat文件,用来方便执行test case:node
run.bat:执行全部的测试用例,很简单就是调用mocha,-t 5000表示,每一个用例5秒超时(默认是2秒)git
@ECHO OFF mocha -t 5000 %1 %2 %3 %4 %5 %6 %7 %8 %9
执行完以后,会看到以下的结果:github
spec.bat:测试,而且显示出每一个测试用例的说明(能够用来生成描述文档,spec这些的),代码更简单,就是调用run.bat,且多加了一个参数,-R spec。(mocha还支持不少其余的报告格式的!)web
@ECHO OFF run -R spec运行以后,能够看到以下结果:
3、测试用例编写很简单,我用的是BDD,assert用的是should库,也是TJ大神的做品,另外用了request库来执行web service:npm
var assert = require("should") , request = require('request') , settings = require('../settings'); describe('Web Service', function () { describe('/', function () { it('should return html content', function (done) { request(settings.webservice_server, function (error, response, body) { if (error) throw error; response.should.status(200).html; done(); }); }); }); describe('/products', function () { it('should return an array of products', function (done) { request(settings.webservice_server + '/products', function (error, response, body) { if (error) throw error; response.should.status(200).json; response.body.should.not.empty; var products = JSON.parse(response.body); products.should.be.an.instanceOf(Array); done(); }); }); }); });对于异步函数,执行完了,就调用下done。