3

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.

5 Answers 5

6

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(); 
          }); 
        }); 
      });
    });
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

looks interesting but the documentation seems non-existent... did you find any useful examples to get up and running?
0

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

Comments

0

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

2 Comments

Not sure how you'd manage firing up the temporary node server using alternate configuration settings using api-easy and/or vows.
how did you try to configure your test?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.