Thursday, March 6, 2014

Testing your HAPI service

For the past few weeks I've been building a REST API with hapi. It's a bit of a mind shift from middleware based frameworks like Express or Django but so far I'm very happy with it. The design really shows that it was made for building serious services.

As far as testing goes I couldn't find much material on how to go about and test my API with, say something like Mocha. I suppose I could've just browsed the hapi source code and see how it was tested internally, but what I ended up doing (after some googling) was that I'd actually start the hapi server before each test case and then stop it after each test. In the tests I used mikeal's request library to query the API. This worked but it felt a bit awkward compared to, for example, what Django provides.

Luckily, I ran into Eran's great talk about hapi where he briefly mentions the server.inject() method. I remember seeing that method before but didn't really understand what it would be good for. But actually with that method you can easily build your API tests.  So, I created a generic function for querying  my API:

/**
 * @param {hapi.Server} server - hapi server instance
 * @param {object} requestobj - options for making the request
 */
exports.request = function (server, requestobj, callback)
    server.inject(requestobj, function (res)
        if (res.payload)
            res.body = JSON.parse(res.payload);
        }
        callback(res);
    });



In the tests I would do something like this (note that the following test uses Mocha but any test framework should do just fine):


    beforeEach(function (done) {
        var api = require('../api/api.js');
        this.server = api.createServer();
        done();
    });


    it('should GET all players', function (done) {
        var request = { url: '/player/', method: 'GET' };
        test.request(this.server, request, function (res) {
            res.statusCode.should.be.equal(200);
            res.body.length.should.be.equal(6);
            done();
        });
    });

And that was it. No more starting and stopping the server all the time.


No comments:

Post a Comment