Calling to next middleware after redirect in Express.js

jne*_*der 4 testing middleware node.js express

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');
  }
};
Run Code Online (Sandbox Code Playgroud)

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.

Jon*_*Ong 6

您在同一个请求中发送两个响应。next()是一个响应,假设下一个处理程序也有一个响应,那么res.redirect(). 你真正想要的是:

var middlewareExample = function(req, res, next){
  if(req.session){
    refreshSession(req.session, next);
  }else{
    res.redirect('/authenticate');
  }
};
Run Code Online (Sandbox Code Playgroud)