Jayesh
Jayesh

Reputation: 999

How can i test async functions using express, mongoose and nodeunit?

How can i use node-mocks-http for testing async? for eg: I have this in my express router which can be reached through GET /category/list

var getData = function (req, res) {
Category.find({}, function (err, docs) {
if (!err) {
    res.json(200, { categories: docs });
} else {
    res.json(500, { message: err });
    }
});
};

and in the test

var request  = httpMocks.createRequest({
    method: 'GET',
    url: '/category/list',
    body: {}
});
var response = httpMocks.createResponse();
getData(request, response);
console.log(response._getData());
test.done();

but the response does not contain the json (response comes back later after a few seconds). How can i test this? Any help is much appreciated.

Upvotes: 0

Views: 257

Answers (1)

Sven
Sven

Reputation: 5265

You can pass a callback parameter to the getData function which executes when Mongoose has returned the data.

var getData = function (req, res, cb) {
  Category.find({}, function (err, docs) {
    if (!err) {
      res.json(200, { categories: docs });
    } else {
      res.json(500, { message: err });
    }
    cb();
  });
};

and then do

var request  = httpMocks.createRequest({
  method: 'GET',
  url: '/category/list',
  body: {}
});
var response = httpMocks.createResponse();
getData(request, response, function() {
  console.log(response._getData());
  test.done();
});

Upvotes: 1

Related Questions