如何在Node.js中testing请求响应周期?

例如,假设我有以下几点

app.get('/', function(req, res) { var ip; if(req.headers['x-forwarded-for']){ ip = req.headers['x-forwarded-for']; } else { ip = req.connection.remoteAddress; } }); 

我想unit testing,看看ip是否被正确检索。 一种方法如下

 function getIp(req) { var ip; if(req.headers['x-forwarded-for']){ ip = req.headers['x-forwarded-for']; } else { ip = req.connection.remoteAddress; } return ip; } app.get('/', function(req, res) { var ip = getIp(req); }); 

现在我有一个函数getIp,我可以unit testing。 不过,我仍然坚持。 如何将一个模拟的req对象提供给getIp?

我只是写集成testing。 Node.js足够快。 特别是当你使用摩卡的手表模式。 你可以使用像superagent或请求执行http请求。

还有一些例如nock来模拟你的http请求。 虽然我从来没有使用过它,因为集成testingtesting真实的东西,速度足够我的口味。

我build议使用摩卡来编写你的unit testing,在这种情况下,你会使用'请求'作为你的http客户端。 但是最简单的入门方法是使用以下方法:

 var http = require('http'); //Change to the ip:port of your server var client = http.createClient(3000, 'localhost'); var request = client.request('GET', '/', {'host': 'localhost'}); request.end(); request.on('response', function (response) { console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); response.setEncoding('utf8'); response.on('data', function (chunk) { console.log('BODY: ' + chunk); }); });