Question

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.

Was it helpful?

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

OTHER TIPS

I've never been able to reliably shut Express programmatically. Instead, I recommend using something like jasmine-before-all to start the server once for all of your integration tests. This also speeds up your tests.

One of the nice things about mocha is that it includes a root suite before and after, which is useful for just this sort of thing. See https://stackoverflow.com/a/18802494/1935918

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top