How to unit test express Router routes

cusejuice picture cusejuice · Feb 5, 2016 · Viewed 28.6k times · Source

I'm new to Node and Express and I'm trying to unit test my routes/controllers. I've separated my routes from my controllers. How do I go about testing my routes?

config/express.js

  var app = express();
  // middleware, etc
  var router = require('../app/router')(app);

app/router/index.js

  module.exports = function(app) {
    app.use('/api/books', require('./routes/books'));
  };

app/router/routes/books.js

  var controller = require('../../api/controllers/books');
  var express = require('express');
  var router = express.Router();

  router.get('/', controller.index);

  module.exports = router;

app/api/controllers/books.js

// this is just an example controller
exports.index = function(req, res) {
    return res.status(200).json('ok');
};

app/tests/api/routes/books.test.js

  var chai = require('chai');
  var should = chai.should();
  var sinon = require('sinon');

  describe('BookRoute', function() {

  });

Answer

ironchefpython picture ironchefpython · May 26, 2016

Code:

config/express.js

var app = express();
// middleware, etc
var router = require('../app/router')(app);

module.exports = app;

app/tests/api/routes/books.test.js

var chai = require('chai');
var should = chai.should();
var sinon = require('sinon');
var request = require('supertest');
var app = require('config/express');

describe('BookRoute', function() {
    request(app)
        .get('/api/books')
        .expect('Content-Type', /json/)
        .expect('Content-Length', '4')
        .expect(200, "ok")
        .end(function(err, res){
           if (err) throw err;
        });
});

Considerations:

If your server requires an initial state at the beginning of a set of tests (because you're executing calls which mutate server state), you'll need to write a function that will return a freshly configured app and the beginning of each group of tests. There is an NPM library: https://github.com/bahmutov/really-need that will allow you to require a freshly instantiated version of your server.