简体   繁体   中英

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.

You can use Supertest

var request = require('supertest')
  , express = require('express');

var app = express();

app.get('/user', function(req, res){
  res.send(200, { name: 'tobi' });
});

request(app)
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '20')
  .expect(200)
  .end(function(err, res){
if (err) throw err;
  });

Using Mocha:

describe('GET /users', function(){
  it('respond with json', function(done){
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  })
})

I suggest you to divide into two file your app: the app.js that contains all your app code and return it with module.exports, and the server.js file that requires app.js and pass it to a new http server listen method. This way you can write tests doing require of app.js.

This is how the default app created with express generator work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM