Search code examples
node.jsexpressjasmine-node

Closing an express server after running jasmine specs


I am trying to set up jasmine testing of my express server. I am spinning up a new server with each spec and trying to shut it down after each spec completes. Unfortunately, the server doesn't seem to be shutting down... making running more than one spec impossible.

server.js:

var app = require('express')();

exports.start = function(config){
  if(!this.server){
    app.get('/', function(req, res){
      res.status(200);
      res.end();
    })

    this.server = app.listen(config.port, function(){
      console.log('Server running on port %d', config.port);
    });
  }
};

exports.close = function(){
  this.server.close();
}

routing-spec.js:

var server = require('./path/to/server.js');
var http = require('http');

describe('express server', function () {
  beforeEach(function () {
    server.start({port: 8000});
  });

  afterEach(function () {
    server.close();
  });

  describe('/', function () {
    it('should return 200', function (done) {
      http.get('http://localhost:8000', function (res) {
        expect(res.statusCode).toBe(200);
        done();
      });
    });
  });
});

The first spec passes as expected but the terminal never completes the test(ie: the server is still running) and any subsequent tests added cause a "ECONNREFUSED" to be thrown.


Solution

  • You can use the npm module server-destroy. server-destroy keeps track of all connections and then closes them when destroy is called. Also, the destroy method takes a callback so you should pass your "done" function to your destroy method... Below is copied from the npm module description with the addition of a callback in the destroy call.

    var enableDestroy = require('server-destroy');
    
    var server = http.createServer(function(req, res) {
      // do stuff, blah blah blah
    });
    
    server.listen(PORT);
    
    // enhance with a 'destroy' function
    enableDestroy(server);
    
    // some time later...
    server.destroy(done);
    

    If open connections are not a problem you can simply pass the done function to the close function, server.close(done) as described in this post How to correctly unit test Express server