Reputation: 33429
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
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
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
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