Fork me on GitHub

koa学习-测试

mocha 模块是测试框架
chai 模块是用来进行测试结果断言库,比如一个判断 1 + 1 是否等于 2
supertest 模块是http请求测试库,用来请求API接口

单元测试

所需测试demo
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const koa = require('koa');
const app = new koa();
const server = async (ctx, next) => {
let result = {
success: true,
data: null
};
if (ctx.method === 'GET') {
if (ctx.url === '/getString.json') {
result.data = 'this is string data';
} else if (ctx.url === '/getNumber.json'){
result.data = 123456;
} else {
result.success = false;
}
ctx.body = result;
next && next();
} else if (ctx.method === 'POST') {
if (ctx.url === '/postData.json') {
result.data = 'ok';
} else {
result.success = false;
}
ctx.body = result;
next && next();
} else {
ctx.body = 'hello world';
next && next();
}
};
app.use(server);
module.exports = app;
app.listen(3004, () => {
console.log('[demo] test-unit is starting at port 3004')
});

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const supertest = require('supertest')
const chai = require('chai')
const app = require('./../index')
const expect = chai.expect
const request = supertest( app.listen() )
// 测试套件/组
describe( '开始测试demo的GET请求', ( ) => {
// 测试用例
it('测试/getString.json请求', ( done ) => {
request
.get('/getString.json')
.expect(200)
.end(( err, res ) => {
// 断言判断结果是否为object类型
expect(res.body).to.be.an('object')
expect(res.body.success).to.be.an('boolean')
expect(res.body.data).to.be.an('string')
done()
})
})
})

参考文档:
koa-note
koa-jsonp

-------------本文结束感谢您的阅读,如果本文对你有帮助就记得给个star-------------
Donate comment here