Setup/teardown of express.js application with mocha

mrmagooey picture mrmagooey · Jun 10, 2012 · Viewed 9.9k times · Source

I'm trying to create a standalone test suite using mocha, that in a perfect world would start up my express.js application, use zombie to render a page, check a bunch of stuff and then teardown/kill the express.js application.

Is there an easy/best way to do this?

NB. I could just have the express application server running prior to running the tests, but what good are Yaks if you're not going to shave them.

Answer

Oved D picture Oved D · Jul 18, 2012

First, you need to move your actual app setting up into a module, and import that into the file that actually starts your app. Now that this is seperate, you can have the app in its complete state before actually listening.

You should move the actual setting up of your app into a separate file, let's call it app.js, can call listen from the file you run node off of, let's call it index.js.

So, app.js would look like:

    var express = require('express')
  , routes = require('./routes');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

and index.js would look like:

var app = require('./app');

app.listen(3000, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});

This seperates loading of your app from actually having it listen, allowing you to load that app into your unit tests.

In your unit tests, you would do something in a setup method and teardown method to bring up and bring down the server.

In the file test/app_tests.js:

describe('app', function(){
  var app = require('../app');
  beforeEach(function(){
    app.listen(3000);
  });
  // tests here
  afterEach(function(){
    app.close();
  })
});