Node.js – 简单的Restify POST摩卡testing失败

我有一个简单的Node.jsrest服务器使用Restify单个POST服务。 我正在尝试编写一个简单的Mochatesting,但是它会失败并且超时,尽pipeREST控制台testing(浏览器插件)成功。

我的服务器代码:

/** * Module dependencies */ var restify = require('restify'); var events = require('events'); var util = require('util'); /** * Create App */ var server = restify.createServer({ name: 'test', version: '0.0.1' }); var eventsEmitter = new events.EventEmitter(); /** * Configuraion */ server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); /** * Routes */ server.post('/post', function (req, res, next) { var text = ""; req.setEncoding("utf8"); req.on("data", function (chunk) { text += chunk; }); req.on("end", function () { res.send(200, {ok: 'ok'}); }); return next(); }); /** * Listen */ server.listen(8080, function () { console.log('%s listening at %s', server.name, server.url); }); 

摩卡testing如下:

 var restify = require('restify'); var assert = require('assert'); // init the test client var client = restify.createJsonClient({ url: 'http://127.0.0.1:8080', version: '*' }); describe('service: post endpoint', function() { // Test #1 describe('200 response check', function() { it('should get a 200 response', function(done) { client.post('/post', { hello: 'world' }, function(err, req, res, data) { if (err) { throw new Error(err); } else { if (data.code != 200) { throw new Error('invalid response from /post'); } done(); } }); }); }); }); 

任何人都可以build议为什么testing会超时(我已经testing增加摩卡超时),但通过浏览器成功?

问题是Restify在请求完成时调用server.post('/post', handler)函数。 您不必等待dataend事件。 这是Restify(和其他类似的图书馆,例如Express)为你做的事情。 所以你所要做的就是写

 server.post('/post', function (req, res, next) { res.send(200, {ok: 'ok'}); }); 

然后你不应该有一个超时。 你有超时,因为你的处理程序正在等待已经发生的事件。