Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtharrison/1990713ecf9adf715d2b74565e78d4f3 to your computer and use it in GitHub Desktop.
Save mtharrison/1990713ecf9adf715d2b74565e78d4f3 to your computer and use it in GitHub Desktop.

An question I've seen several times popping up in hapi issues is how to get an initialized hapi server into your tests. There's a few patterns I've seen in common use so I thought I'd document them somewhere.

Here's the test we're going to use as an example:

it('Can add two numbers', (done) => {

    server.inject('/add/1/5', (res) => {
  
        expect(res.statusCode).to.equal(200);
        expect(res.result).to.equal(6);
        done();
    });
});

Pattern 1 - The exported server with module check

This is probably my least favourite pattern, but it seems very common so I've included for completeness.

In this case, we export the server object from our main server script and import into our tests. But we check in the script if it's being imported as a module versus run as a script, and only start the server if this is a script.

index.js

const Hapi = require('hapi');
const server = new Hapi.Server();

server.connection({ ... });

server.route({
    method: 'GET',
    path: '/add/{a}/{b}',
    handler: function (request, reply) {
        
        const { a, b } = request.params;
        return reply(a + b);
    }
});

server.register([...], (err) => {

    if (err) {
        throw err;
    }
    
    if (!module.parent) {
        server.start((err) => {
    
            if (err) {
                throw err;
            }
            
            // server ready!
        });
    }
}); 

module.exports = server;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment