I am looking to drive behavior through integration tests on an Express.js middleware. I have encountered an interesting circumstance where the behavior of Express behind the application is not predictable (not by me, anyway).
As a simplified example:
var middlewareExample = function(req, res, next){
if(req.session){
refreshSession(req.session, function(err, data){
if(!err){
res.redirect('/error');
}
});
next();
}else{
res.redirect('/authenticate');
}
};
The issue is the call to next
following the redirect, as it lives outside of the inner function and conditional. I am not certain how Express handles middleware/route calls to next
or res.redirect
if they happen to take place before or after one another as seen above.
Manual testing has not revealed any strange behavior, nor has the supertest module. I would like to know if and how Express responds to circumstances such as this. Also, can supertest can be used to expose any potential unwanted behavior. Additionally, if I may, I would like to hear what approaches others would use to test Node/Express middleware in general.
you are sending two responses in the same request. next()
is a response, assuming the next handler has a response as well, and so is res.redirect()
. What you really want is:
var middlewareExample = function(req, res, next){
if(req.session){
refreshSession(req.session, next);
}else{
res.redirect('/authenticate');
}
};