node.js:模拟http请求和响应

7el*_*ant 34 mocking node.js express

是否有方便的方法来模拟单元测试中间件的HTTP请求和响应对象?

mjs*_*mjs 25

看起来https://github.com/howardabrams/node-mocks-httphttps://github.com/vojtajina/node-mocks都可用于创建模拟http.ServerRequesthttp.ServerResponse对象.


Ric*_*aca 7

从标签看,这个问题看起来像是Express.在那种情况下,supertest非常好:

var request = require('supertest')
  , express = require('express');

var app = express();

app.get('/user', function(req, res){
  res.send(201, { name: 'tobi' });
});

request(app)
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '20')
  .expect(201)
  .end(function(err, res){
    if (err) throw err;
  });
Run Code Online (Sandbox Code Playgroud)

对于一般节点使用,Flatiron Nock看起来是个不错的选择:

var nock = require('nock');
var example = nock('http://example.com')
                .get('/foo')
                .reply(200, { foo: 'bar' });

var http = require('http');
var options = {
  host: 'example.com',
  port: 80,
  path: '/foo',
  method: 'GET'
}
var req = http.request(options, function(res) {
  res.on('data', function(chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('error: ' + e);
});

req.end();
Run Code Online (Sandbox Code Playgroud)

输出:

BODY:{"foo":"bar"}


Ter*_*ska 2

我正在使用nodejutsu模拟:

https://github.com/nodejitsu/mock-request

也许这就是您正在寻找的。

  • 该项目已被弃用。建议使用“nock” https://github.com/flatiron/nock (4认同)