express测试

1.测试API

一个API基本上是一系列的代码块逻辑组成的,而对于mocha和chai来说,一般只是用来测试某个函数,所以就测试场景来说不是特别适合。因此有了Supertest,Supertest就不一样了,对于API测试来说,它会向server发送一个请求,自然的,server会对我们的请求作出响应,一旦做出了响应,那么我们便可以对响应进行断言,以此来测试响应数据是否正确。

2.关键库supertest

示例代码如下所示:

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
// test.js
const app = require('../app');
const supertest = require('supertest');
const cheerio = require('cheerio');

describe('html test', function() {
let request;

beforeEach(function() {
request = supertest(app)
.get('/html')
.set('User-Agent', 'cool supertest')
.set('Accept', 'text/html')
});

it('return html response', function (done) {
request
.expect('Content-Type', /text\/html/)
.expect(function(res) {
let $ = cheerio.load(res.text);
let domContent = $(query).text(); // 获取query处的content
if (domContent !== 'CONTENT_YOU_WANT') {
throw new Error('content do not match');
}
})
.expect(200)
.end(done);
});
});