使用Mocha对node项目接口进行单元测试
一.安装Mocha,supertest并配置Mocha
npm i mocha supertest -D
在package.json的script.test
注意配置--exit
操作符可以运行完毕后自动关闭运行脚本
{
"scripts": {
"test": "mocha --exit"
}
}
二.实战测试项目接口
1. 简单写一个服务器
//app.js
const Koa = require('koa2');
const app = new Koa();
app.use((ctx,next)=>{
ctx.response.type = 'text/html';
ctx.body = `${ctx.url}`;
});
module.exports = app;
2. 写测试代码
//app.test.js
const
request = require('supertest'),
app = require('../app');
describe('#test koa app',function(){
let server = app.listen(9900);
describe('#test server',function(){
it('#test GET /',async function(){
await request(server).get('/sky').expect(200,'/sky');
})
})
})
3. 进行测试
skymac@skymacdeMBP machajs % npm test
> machajs@1.0.0 test /Users/skymac/Desktop/all-demo/machajs
> mocha
#test koa app
#test server
(node:23361) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated
✓ #test GET /
1 passing (25ms)