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