node.jsmocha.js

Run mocha tests in test environment?


I can't seem to tell mocha to run my test suite in the test environment.

app.js

app.configure('test', function(){
  app.set('port', 3002);
});

test/some-test.coffee

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

process.env.NODE_ENV = 'test'

describe 'some test', ->
  it 'should pass', ->

Since I'm requiring app, when I run the tests I expect to see

Express server listening on port 3002

and instead I see

Express server listening on port 3000

Setting a different port number in a development configuration block in app.js yields

Express server listening on port [whatever port I set in development block in app.js]

I cannot get my tests to run in a test environment. Any suggestions?


Solution

    1. You need to define NODE_ENV before you require app.js:

      process.env.NODE_ENV = 'test'
      
      app = require('../../app')
      
      describe 'some test', ->
        it 'should pass', ->
      
    2. You can't change listening port by app.set. There is only one way to set port - pass it into listen method. You can do something like this:

      var express = require('express');
      var app = express();
      
      app.get('/', function(req, res){
        res.send('hello world');
      });
      
      var port = 3000;
      
      app.configure('test', function(){
        port = 3002;
      });
      
      app.listen(port);