danfromisrael
danfromisrael

Reputation: 3112

TDD Test first Nodejs express Rest Api - unit testing middlewere / controllers / routes

I'm trying to figure out how to test first my node js rest api app. so far i've been using nock to intercept and mock any http call and by that test my service as a component. (component testing?) i want to start unit testing my app so my test pyramid is more balanced and tests will be easier to write.

searching the web i got to this approach: http://www.slideshare.net/morrissinger/unit-testing-express-middleware

var middleware = require('./middleware');
app.get('example/uri', function (req, res, next) {
  middleware.first(req, res)
    .then(function () { next(); })
    .catch(res.json)
    .done();
}, function (req, res, next) {
  middleware.second(req, res)
    .then(function () { next(); })
    .catch(res.json)
    .done();
});

(basicly pulling the middleware out and testing it)

since this presentation is from 2014 i was wondering what are the current up to date methods for unit testing express apps?

Upvotes: 1

Views: 561

Answers (1)

Antonio Ganci
Antonio Ganci

Reputation: 515

I had the same problem and I used another approach. First I created a file included in all my tests that start node and export a function to send an http request:

process.env.NODE_ENV = 'test';
var app = require('../server.js');

before(function() {
  server = app.listen(3002);
});

after(function(done) {
 server.close(done);
});

module.exports = {
  app: app,
  doHttpRequest: function(path, callback) {
    var options = {
      hostname: 'localhost',
      port: 3002,
      path: path,
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': 0
      }
    };

    var req = http.request(options, 
      function(response) {
        response.setEncoding('utf8');

        var data = '';
        response.on('data', function(chunk) {
          data += chunk;
        });

        response.on('end', function() {
          callback(data, response.statusCode);
        });
      });

    req.end();     
  }
}

Then I called my server using the previous declared method:

var doHttpRequest = require('./global-setup.js').doHttpRequest;
var expect = require('chai').expect;

describe('status page test', function() {

  it('should render json', function(done){
    doHttpRequest('/status', function(response) {
      expect(JSON.parse(response).status).to.eql('OK');
      done();
    })
  });
});

Upvotes: 2

Related Questions