Feature: Heartbeat
As an administrator I want to visit an endpoint So that I can confirm the server is responding
Let's add a test to ./test/heartbeat.js
for our Heartbeat
feature. This resource will get a status from the route /heartbeat
and return a 200 Ok
status code. Let's write our first integration test using Mocha and SuperTest. First off, create a folder named /test
inside your vision
folder.
Our test describes heartbeat
; it expects the response to have a JSON
content type and a status code equal to 200 Ok
.
var app = require('../app') , request = require('supertest'); describe('vision heartbeat api', function(){ describe('when requesting resource /heartbeat', function(){ it('should respond with 200', function(done){ request(app) .get('/heartbeat') .expect('Content-Type', /json/) .expect(200, done); }); }); });
Let's implement the Heartbeat
feature; we start by creating a simple Express server, ./lib/express/index.js
. We include the express
and http
modules and create an Express application. We then add an application setting via app.set
called port
and set it to 3000
. We define a /heartbeat
route via app.get
with
which we pass a request handler, function
, that takes two parameters: req
(request) and res
(response). We use the response object to return a JSON response. We create an HTTP server with http.createServer
by passing our Express application to it; we listen on port 3000
as defined in our application setting called port
. We then export the application with module.exports
; exporting the application allows us to test it.
var express = require('express') , http = require('http') , app = express(); app.set('port', 3000); app.get('/heartbeat', function(req, res){ res.json(200, 'OK') }); http.createServer(app).listen(app.get('port')); module.exports = app;
We now create ./app.js
in the root of our project and export the express
module:
module.exports = require('./lib/express');
To run our test, execute the following command:
mocha
You should then receive the response:
1 tests complete (14 ms)
If successful, try running the application by executing this command:
npm start
With the app running, run the following curl
command in a new terminal and you can see our heartbeat
JSON response return a 200 Ok
status code:
curl -i http://127.0.0.1:3000/heartbeat HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 4 Date: Fri, 14 Jun 2013 08:28:50 GMT Connection: keep-alive