How to unit test a NodeJs REST API server built using Express + Mongoose?
I use Jenkins (continuous integration server) and Mocha to test my app, and I found myself having the same problem as you. I configured Jenkins so it would execute this shell command:
npm installNODE_ENV=testing node app.js &npm mochapkill node
This runs the server for executing the tests, and then kills it. This also sets the NODE_ENV environment variable so I can run the server on a different port when testing, since Jenkins already uses port 8080.
Here is the code:
app.js:
...var port = 8080if(process.env.NODE_ENV === "testing") port = 3000;...
test.js:
var request = require('request'), assert = require('assert'); describe('Blabla', function() { describe('GET /', function() { it("should respond with status 200", function(done) { request('http://127.0.0.1:3000/', function(err,resp,body) { assert.equal(resp.statusCode, 200); done(); }); }); }); });