2

I see some similar questions, but my setup is slightly different and I can't figure out a good way to test this.

I'm trying to test that my express app routes are directed to the correct controller methods.

For example -

//server.js, base application

var express = require("express");
var app = express();
require("./routes.js")(app);
...

//routes.js
var menuController = require("./controllers/menu.js");

module.exports = function(expressApp) {
    expressApp.get('/menu', menuController.getMenu);
};
...

//test file
var express = require('express')
    , menuController = require("../../controllers/menu.js")
    , chai = require('chai')
    , should = chai.should()
    , sinon = require('sinon')
    , sinonChai = require("sinon-chai");
chai.use(sinonChai);

var app = express();
require("../../routes/routes.js")(app);

describe('routes.js', function(){

    it('/menu should call menuController.getMenu route', function(){
        var spy = sinon.spy(menuController, 'getMenu');
        app.get('/menu', spy);

        spy.should.have.been.called;  //fails, never called
    });

});  

How can I check to see that when calling app.get('/menu', ..), the callback from menuController is invoked? Or should I restructure the app somehow (I see a bunch of other ways to configure the routing)?

Community
  • 1
  • 1
Justin Maat
  • 1,965
  • 3
  • 23
  • 33

2 Answers2

0

Instead of doing that I would suggest checking the response code that comes back from /menu and also checking the response itself that it requals or contains a known response.

Jeff Sloyer
  • 4,899
  • 1
  • 24
  • 48
  • That would be more of an integration test. Although, I understand what you're saying and have unit tests for the actual server.js and menuController. So yes, I'm covering the check of the response codes (ie. implementation of the controller methods). But I want to also test that the routes are configured properly - ex: someone goes and changes a route , maybe a typo, so the test will error. – Justin Maat Mar 11 '15 at 15:44
0

It won't be truly unit test but you can do that, this way:

Use dependency injection like this:

function bootstrapRouterFactoryMethod(bootstrapController) {
    var router = express.Router();
    router.route('/').post(bootstrapController.bootstrap);
    return router;
};

module.exports = bootstrapRouterFactoryMethod;

And then pass fake as a bootstrapController and verify if bootstrap method is called.

var request = require('supertest');

...

it('calls bootstrapController #bootstrap', function (done) {
    var bootstrapControllerFake = {
        bootstrap: function(req, res) {
            done();
        }
    };
    var bootstrapRouter = bootstrapRouterFactoryMethod(bootstrapControllerFake);
    app.use(bootstrapRouter);
    request(app).post('/').end(function (err, res) {});
});