HTTP测试----supertest

734 查看

前言

在做nodejs开发中,难免会遇到HTTP相关的测试,一般需要依赖模块supertest或者superagent,supertest依赖后者。

The motivation with this module is to provide a high-level abstraction for testing HTTP。

先从介绍说起,supertest提供HTTP测试抽象接口。本质上来说,是直接向接口发起HTTP请求并解析结果,然后针对结果进行assert

参考文档

中间件测试示例----bodyparse.json

bodyparse的作者测试用例跟我最初的思考有差异,但更简洁。原作者将中间件直接在createserver回调函数中使用,此时的三个参数在实际使用时由express进行控制,此处是显式声明。

function createServer(opts){
  var _bodyParser = bodyParser.json(opts)
  return http.createServer(function(req, res){
    _bodyParser(req, res, function(err){
      res.statusCode = err ? (err.status || 500) : 200;
      res.end(err ? err.message : JSON.stringify(req.body));
    })
  })
}

var http = require('http');
var request = require('supertest');
var bodyParser = require('..');

describe('bodyParser.json()', function(){
  it('should parse JSON', function(done){
    var server = createServer({ limit: '1mb' })
    request(server)
    .post('/')
    .set('Content-Type', 'application/json')
    .send('{"user":"tobi"}')
    .expect(200, '{"user":"tobi"}', done)
  })

私以为,中间件只需要做好输入输出即可,所以我在测试时,依旧引入了express,并在jsonBodyParse路由下调用中间件,然后添加响应函数,返回req.body,觉得这样更适应自己的风格。

var requestAgent = require('supertest');
var should = require('should');
var mocha = require('mocha');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.post('/jsonBodyParse', bodyParser.json(), function(req, res) {
    res.send(req.body);
});
var request = requestAgent(app);

describe('reverse flower', function() {
    it('post path /jsonBodyParse', function(done) {
        request
            .post('/jsonBodyParse')
            .type('application/json')
            .send('{"name":"jason"}')
            .expect(200, {"name":"jason"})
            .end(function(err) {
                done(err);
            });
    });
});

后记

HTTP测试依赖模块并不复杂,也是刚接触不久,不定时更新此文。