pathikrit
pathikrit

Reputation: 33429

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.

Upvotes: 3

Views: 6046

Answers (5)

Luis Hernan Paul
Luis Hernan Paul

Reputation: 61

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 install
NODE_ENV=testing node app.js &
npm mocha
pkill 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 = 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(); 
          }); 
        }); 
      });
    });

Upvotes: 6

hboylan
hboylan

Reputation: 397

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

Upvotes: 0

norman784
norman784

Reputation: 2221

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

Upvotes: 0

pathikrit
pathikrit

Reputation: 33429

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.

Upvotes: 1

Amir
Amir

Reputation: 1872

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

Upvotes: 0

Related Questions