samedi 30 mai 2015

Unit testing expressjs application

I have the following module that I'm working on adding unit tests for. Basically I want to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), I also want to ensure that app.listen is called with the correct port.

function WebService(express, logger) {
    this.express = express;
    this.log = logger;
    this.port = 3000;
}

// init routes and start the server
WebService.prototype.start = function start() {    
    var app = this.express();

    // Setup routes
    app.use('/', this.express.static('www/html'));

    // Startup the server
    app.listen(this.port);

    this.log.info('Starting webserver on port %s', this.port);

};

module.exports = WebService;

If I remove the app.use (replace with a simple app.get) I can get the listen tested by passing this into the constructor in the unit test

var express_stub = function() {
                var tmpObj = {
                    get: function() {},
                    listen: listen_stub // sinonjs stub
                };
                return tmpObj;
            };

When I switch over to using this.express.static in the route, this falls over (expectedly because this.express doesn't define static) I can't quite get my head wrapped around the correct way to deal with this. The this.express() as the constructor is really throwing me. I can't figure out the correct way to mock the calls I want to validate in express.

Aucun commentaire:

Enregistrer un commentaire