How to unit test a NodeJs REST API server built using Express + Mongoose?

I have a REST API server that uses Express, Mongoose and config. I want to unit test my API. Basically, bring up a temporary web server on port x, an empty mongo-database on port y, do some API calls (both gets and puts) and validate what I get back and then shutdown temporary server and drop test database once my tests finish. What is the best way to do this? I have been looking at mocha/rewire but not sure how to set up temporary server and db and not sure what the best practices are.

I use jenkins(continuous integration server) and mocha to test my app and i found myself in the same problem as you. What i did was to configure jenkins so it would execute this shell command:

npm install
NODE_ENV=testing node app.js &
npm mocha
pkill node

What i do here is run the server for doing the testing and then kill it. Also I seted an enviroment variable so i could run the server in a different port when testing(because jenkins already uses port 8080).Heres is the code:

app.js:

...
var port = 8080
if(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(); 
            }); 
        }); 
    });
});

I found exactly what I was looking for: testrest. I don't like its .txt file based syntax - I adapted to use a .json file instead for my specs.

I'd recommend giving Buster.JS a try. You can do Asynchronous tests, mocks/stubs, and fire up a server.

There its also api-easy build on top of vows, seems to be easy to use the first, but the second its much flexible and powerful

There is no right way, but I did create a seed application for my personal directory structure and includes the vows tests suggested by @norman784.

You can clone it: git clone https://github.com/hboylan/express-mongoose-api-seed.git

Or with npm: npm install express-mongoose-api-seed