在node开发中,写完了API接口之后,往往都要进行测试,现在常用的测试模块一般都是mocha和chai,
然后我们应该有相配合的请求模块来帮助我们更好地完成断言的工作,今天要介绍的主角就是supertest
用过superagent的童鞋应该都知道,supertest的用法同样简洁优雅,本文环境基于Express,废话不说,上实战代码
GET 请求
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 assert = require('chai').assert; const request = require('supertest'); const should = require('should'); const app = require('../../app'); const _ = require('lodash');
describe("get /", function() { it("should respond with ....", function() { return request(app).get('/') .set('Accept', 'application/json') .expect(200) .then(function(res) { assert.notEqual(_.findIndex(res.body, { 'key' : 'value' }), -1); }) }) }
|
POST 请求
1 2 3 4 5
| return request(app).post('/search') .send({ key: 'value' }) .field('name', 'Jack') .attach('avatar', 'test/fixtures/homeboy.jpg')
|
PUT或DELETE请求
同理
1 2
| request(app).del('/path') request(app).put('/path')
|