Ben Ben - 26 days ago 14
Node.js Question

Node.js - simple Restify POST Mocha test failing

I have a simple Node.js Rest server with a single POST service using Restify. I am trying to write a simple Mocha test, however it fails with a timeout, although succeeds with a REST Console test (browser plugin).

My server code:

/**
* 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);
});


The Mocha test is as follows:

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();
}
});
});
});

});


Can anyone advise why the test would timeout (I have tested with increasing the timeout in Mocha), but succeed through a browser?

Max Max
Answer

The problem is that Restify calls your server.post('/post', handler) function when the request is finished being received. You don't have to wait for the data and end events. It is something that Restify (and other libraries like it, eg. Express) do for you. So all you need to do is write

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

And then you should not have a timeout. You were having the timeout because your handler was waiting for events that already came.

Comments