学习写单元测试
服务器端的测试
mocha
Mocha是一个在Node.js和浏览器上运行的功能丰富的JavaScript测试框架,使异步测试变得简单而有趣。Mocha测试以串行方式运行,允许灵活准确的报告,同时将未捕获的异常映射到正确的测试用例。 ——mochajs.org
安装
全局安装npm:
$ npm install --global mocha
或者作为项目的开发依赖项:
$ npm install --save-dev mocha
配置package.json
"scripts": {
"test": "mocha"
},
should
这些文档中显示的BDD样式 断言库
$ npm install --save-dev should
supertest
api跟superagent的api一样的
npm install supertest --save-dev
e.g.
const supertest = require('supertest');
const express = require('express');
const app = express();
const request = supertest(app);
app.get('/user', function(req, res) {
res.status(200).json({ name: 'john' });
});
request
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});
整体的例子
// app.js
const express = require('express')
var fibonacci = function(n) {
if(typeof n !== 'number'||isNaN(n)) {
throw Error('n should be a number');
}
if(n>10) {
throw Error('n should < 10')
}
if(n<0) {
throw Error('n should >= 0')
}
if(n===0) {
return 0;
}
if(n===1) {
return 1;
}
return fibonacci(n-1)+fibonacci(n-2);
}
const app = express()
app.get('/fib', function(req, res) {
try {
var n = Number(req.query.n)
res.send(String(fibonacci(n)))
} catch (error) {
res.status(500)
.send(error)
}
})
var port = 8000;
app.listen(port, function(){
console.log(`app is running at ${port}`)
})
module.exports = app
// test/test.js
const supertest = require('supertest')
const app = require('../server')
const request = supertest(app)
const should = require('should')
describe('tet/test.js', function(){
it('should return 55 when n is 10', function(done){
request.get('/fib')
.query({n: 10})
.end((err, res)=>{
res.text.should.equal('55')
})
})
var testFib = function(n, statusCode, expect, done) {
request.get('/fib')
.query({n: n})
.expect(statusCode)
.end((err, res)=>{
res.text.should.equal(expect)
done(err)
})
}
it('should return 0 when n === 0', function (done) {
testFib(0, 200, '0', done);
});
it('should equal 1 when n === 1', function (done) {
testFib(1, 200, '1', done);
});
it('should equal 55 when n === 10', function (done) {
testFib(10, 200, '55', done);
});
it('should throw when n > 10', function (done) {
testFib(11, 500, 'n should <= 10', done);
});
it('should throw when n < 0', function (done) {
testFib(-1, 500, 'n should >= 0', done);
});
it('should throw when n isnt Number', function (done) {
testFib('good', 500, 'n should be a Number', done);
});
it('should status 500 when error', function(done){
request.get('/fib')
.expect(500)
.query({n: 100})
.end((err, res)=>{
done(err)
})
})
})
最后执行
npm test
浏览器端的测试
参考网址: