JamesEggers JamesEggers - 2 months ago 11
Node.js Question

How does one unit test routes with Express?

I'm in the process of learning Node.js and have been playing around with Express. Really like the framework;however, I'm having trouble figuring out how to write a unit/integration test for a route.

Being able to unit test simple modules is easy and have been doing it with Mocha; however, my unit tests with Express fail since the response object I'm passing in doesn't retain the values.

Route-Function Under Test (routes/index.js):

exports.index = function(req, res){
res.render('index', { title: 'Express' })
};


Unit Test Module:

var should = require("should")
, routes = require("../routes");

var request = {};
var response = {
viewName: ""
, data : {}
, render: function(view, viewData) {
viewName = view;
data = viewData;
}
};

describe("Routing", function(){
describe("Default Route", function(){
it("should provide the a title and the index view name", function(){
routes.index(request, response);
response.viewName.should.equal("index");
});

});
});


When I run this, it fails for "Error: global leaks detected: viewName, data".


  1. Where am I going wrong so that I can get this working?

  2. Is there a better way for me to unit test my code at this level?



Update
1. Corrected code snippet since I initially forgot "it()".

Answer

Change your response object:

var response = {
    viewName: ""
    , data : {}
    , render: function(view, viewData) {
        this.viewName = view;
        this.data = viewData;
    }
};

And it will work.