Run mocha tests in test environment?
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', ->
You can't change listening port by
app.set
. There is only one way to set port - pass it intolisten
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.
Add dotenv as a
dependency
in yourpackage.json
file then install the new packages into yournode_modules
folder:package.json
{ ... "dependencies": { ... "dotenv": "0.2.8" } }
command line
$ npm install
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);
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 withprocess.env.
..env
port=3000
.env.test
port=3002
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
.