Testing Node.js api with mocha -


i busy building functional tests existing nodejs api wrote. using mocha , expect.js.

one test failing when want negative test existence of url parameter. want send message the consumer of service if param missing.

currently positive test have works:

var request = require('request');  it('get specific user api', function (done) {     request.get('http://localhost:8080/api/v1/user/123', function (error, response, body) { ... }); }); 

however, following not work , timeout:

it('should return 400 message if userid not supplied stating "userid expected"', function(done) {     request.get('http://localhost:8080/api/v1/user/', function (error, response, body) {          if (!error && response.statuscode == 400) {             expect(body).to.be.equal('userid expected');             done();         }     }); }); 

both above tests testing endpoint:

app.get('/api/v1/user/:userid', function (req, res) {     if(!req.params.userid) {         return res.status(400).json('userid expected');     }      ... user , return status 200 ... }); 

however, stated before, first test successful while second test times out.

update 1: additionally, getting following output:

get /api/v1/user/123 200 2.905 ms - 274 /api/v1/user/ - - ms - - 

update 2: adding following code solves problem, doesn't solve problem:

app.get('/api/v1/user', function (req, res) {     return res.status(400).json('userid expected'); }); 

obviously don't want rather redundant piece of code sitting around. baffled why cannot enter 'api/v1/user/:userid' endpoint , test existence of :userid in there? it's if nodejs requiring existence of :userid, otherwise endpoint not exist. correct?

what missing?

according mocha documentation done callback must called, in case of errors. in fact accepts error. think must rewrite code with:

it('should return 400 message if userid not supplied stating "userid expected"', function(done) {     request.get('http://localhost:8080/api/v1/user/', function (error, response, body) {         if (error) return done(error);         if (response.statuscode != 400) return done(new error("not 400"));          expect(body).to.be.equal('userid expected');         done();     }); }); 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -