Instantly share code, notes, and snippets.

Embed
What would you like to do?

A simple example of testing a hapi.js server that calls another service.

Setup

npm install

Run the server

node server.js

Run the tests

npm run test

{
"name": "hapi-request",
"main": "server.js",
"scripts": {
"test": "lab -v test.js"
},
"devDependencies": {
"code": "^1.3.0",
"lab": "^5.2.1",
"sinon": "^1.12.2"
},
"dependencies": {
"boom": "^2.6.1",
"hapi": "^8.2.0",
"request": "^2.53.0"
}
}
var Hapi = require('hapi')
var Boom = require('boom');
var request = require('request');
var server = module.exports = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8080
});
server.route({
path: '/',
method: 'GET',
handler: function(req, reply) {
request.get('http://date.jsontest.com', function(err, response, content) {
if (err) {
return reply(Boom.wrap(err));
}
switch(response.statusCode) {
case 200:
return reply(JSON.parse(content).date);
case 404:
return reply(Boom.notFound());
default:
return reply(Boom.create(500));
}
});
}
});
if (!module.parent) {
server.start(function() {
console.log('started');
});
}
var Hapi = require('hapi'),
Boom = require('boom'),
Lab = require('lab'),
Sinon = require('sinon'),
server = require('./server.js'),
request = require('request'),
lab = exports.lab = Lab.script(),
code = require('code'),
describe = lab.experiment,
it = lab.it,
beforeEach = lab.beforeEach,
afterEach = lab.afterEach,
expect = code.expect;
describe('server', function() {
var options = {
url: '/',
method: 'GET'
};
var requestStub;
beforeEach(function(done) {
requestStub = Sinon.stub(request, 'get');
done();
});
afterEach(function(done) {
requestStub.restore();
done();
});
it('makes the request', function(done) {
requestStub.yields(null, {statusCode: 200}, '{}');
server.inject(options, function(response) {
var requestUrl = requestStub.getCall(0).args[0];
expect(requestUrl).to.equal('http://date.jsontest.com');
done();
});
});
it('returns the date', function(done) {
requestStub.yields(null, {statusCode: 200}, JSON.stringify({date: '02-17-2015'}));
server.inject(options, function(response) {
expect(response.statusCode).to.equal(200);
expect(response.result).to.equal('02-17-2015');
done();
});
})
it('handles a 404 status', function(done) {
requestStub.yields(null, {statusCode: 404});
server.inject(options, function(response) {
expect(response.statusCode).to.equal(404);
done();
});
});
it('handles an unexpected status', function(done) {
requestStub.yields(null, {statusCode: 401});
server.inject(options, function(response) {
expect(response.statusCode).to.equal(500);
done();
});
});
it('handles an error', function(done) {
requestStub.yields(new Error());
server.inject(options, function(response) {
expect(response.statusCode).to.equal(500);
done();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment