Instantly share code, notes, and snippets.

Embed
What would you like to do?
Complete files for my article, Testing Hapi.js APIs. https://sethlopez.me/article/testing-hapi-js-apis
{
"name": "testing-hapi-js-apis",
"version": "1.0.0",
"license": "MIT",
"scripts": {
"test": "ava --verbose test.js"
},
"dependencies": {
"ava": "^0.16.0",
"hapi": "^15.1.1"
}
}
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 8080 });
server.route({
method: 'POST',
path: '/subscribe',
handler: (request, reply) => {
if (!request.payload.email) {
return reply({
result: 'failure',
message: 'Email address is required.'
}).code(400);
} else if (!/@/.test(request.payload.email)) {
return reply({
result: 'failure',
message: 'Invalid email address.'
}).code(400);
}
// persist the email address
// ...
return reply({
result: 'success',
message: 'Subscription successful.'
});
}
});
if (!module.parent) {
server.start(error => {
process.exit(1);
});
}
module.exports = server;
import test from 'ava';
import server from './server';
const requestDefaults = {
method: 'POST',
url: '/subscribe',
payload: {}
};
test('endpoint test | POST /subscribe | empty payload -> 400 Bad Request', t => {
const request = Object.assign({}, requestDefaults);
return server.inject(request)
.then(response => {
t.is(response.statusCode, 400, 'status code is 400');
});
});
test('endpoint test | POST /subscribe | invalid email address -> 400 Bad Request', t => {
const request = Object.assign({}, requestDefaults, {
payload: {
email: 'a'
}
});
return server.inject(request)
.then(response => {
t.is(response.statusCode, 400, 'status code is 400');
});
});
test('endpoint test | POST /subscribe | valid email address -> 200 OK', t => {
const request = Object.assign({}, requestDefaults, {
payload: {
email: 'test@example.com'
}
});
return server.inject(request)
.then(response => {
t.is(response.statusCode, 200, 'status code is 200');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment