Run mocha tests in test environment?

  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);
    

I would take a different approach from Vadim. Using Vadim's example you could instead load environment settings based on your process.env.NODE_ENV value. I know there is another step in my approach, but it is cleaner, extensible, and will prevent the addition of test conditionals in your logic.

This approach uses dotenv, then defining both a default and a test environment file in the root of the application. These files will allow you to reconfigure properties within your application without changing your JavaScript.

  1. Add dotenv as a dependency in your package.json file then install the new packages into your node_modules folder:

    package.json

    {
      ...
      "dependencies": {
        ...
        "dotenv": "0.2.8"
      }
    }
    

    command line

    $ npm install
    
  2. Change your app.js so that the port is using an environment value set from the loaded .env file.

    // Load .env files from root based on the NODE_ENV value
    require('dotenv').load();
    
    var express = require('express');
    var app = express();
    
    app.get('/', function(req, res){
      res.send('hello world');
    });
    
    var port = process.env.port || 3000;
    -----------^
    
    app.listen(port);
    
  3. Create two files in your folder root, .env & .env.test, just add the one line below. These files have simple key value pairs on each line which can be accessed when prefixed with process.env..

    .env

    port=3000
    

    .env.test

    port=3002
    
  4. From the command line or when you call your tests I would set NODE_ENV:

    $ NODE_ENV=test mocha <TEST_FOLDER>/*.js
      ---------^
    

When you run the application in all other cases without setting NODE_ENV, the values in the default .env file will be loaded into process.env.