HTTP testing in Node with preq

January 03, 2015

The preq Node package makes HTTP testing a breeze. Let's walk through the testing and development of a Node HTTP server.

Prerequisites

To keep things simple, we'll skip package.json and do everything directly from the command line. First, let's install some libraries:

npm install nodeunit # for great testing
npm install preq     # http request library

These are directly available if ./node_modules/.bin is included in the environment path:

export PATH=$PATH:./node_modules/.bin

The test

Let's write a test. We'll be building an HTTP api that exposes an endpoint to add a couple of numbers:

Request:

Response:

Our test uses preq.get to submit the example request, and then access the response:

'/api/add': function (test) {
  test.expect(3);
  preq.get({ uri: 'http://localhost:' + port + '/api/add?a=31&b=11' })
  .then(function (res) {
    test.equal(res.status, 200);
    test.equal(res.headers['content-type'], 'text/plain');
    test.equal(res.body, '31 + 11 = 42');
    test.done();
  });
}

This test won't pass yet, because we haven't writen the server implementation. Let's do that now.

The server

The server will be a standard Node HTTP server, and will use the url package to route based on the request URL:

var server = http.createServer(
  function router(req, res) {
    var parsedUrl = url.parse(req.url, true);
    if (parsedUrl.pathname === '/api/add') {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      var a = parseInt(parsedUrl.query.a);
      var b = parseInt(parsedUrl.query.b);
      var c = a + b;
      res.write(a + ' + ' + b + ' = ' + c);
    }
    res.end();
  }
);

Finally we can our test for a spin.

Testing

To run the test from the command line, we'll use nodeunit:

nodeunit test

server_test
✔ service - /api/add

OK: 3 assertions (463ms)