vendredi 6 février 2015

Unit testing promise based code in node.js express route/controller

Recently I switched from using callbacks to using promise in my rest api express app. But I'm having trouble with unit testing routes/controller with async behaviour of the promise. Here is the sample code that needs to be unit tested.



var handler = function (req, res, next) {
var query = {},
var options = {
sort: { updatedAt: -1 },
limit: 10
};
if (req.query.before) {
query.updatedAt = { $lt: req.query.before };
}
// User.findAsync returns bluebird promise
User.findAsync(query, null, options).then(function (user) {
res.json(user);
}).catch(function (e) {
next(e);
});
}
router.get('/api/users', handler);


My approach to test above code was to spy on req, next, and User.findAsync and check if they are called with correct arguments. But because of async behaviour of the promise, I was having trouble to check if res.json or next are get called.


I've tried to stub findAsync to return resolved promise (Promise.resolve(user)). but still then callback is executed asynchronously.


I'm not sure if I'm on the right track for testing express application.


What is good strategy to test this kind of code in good separation?


I've also heard about using supertest. But for me, Using supertest to test from http end point feels like more of integration testing which is not unit testing and is quite expensive.


Also, In general, I would like to know if it is good practice to try to cover all of the code with unit testing (models, controller, middleware, etc) and what's good strategies or techniques of doing that. Or If it is just good enough to test http end points with super test.


Aucun commentaire:

Enregistrer un commentaire