title: send authenticated request via supertest with mocha on a passport managed API
body: <p>It's been 24 hours since I first had this issue. I know there plenty of similar ones, specially on SO but I can't figure out how to solve it.</p>
  
  <p>I have specific requirement :</p>
  
  <ul>
  <li>I have some routes to test without authentication.</li>
  <li>I have some routes to test with specific users.</li>
  <li>I use a passport local strategy.</li>
  </ul>
  
  <p>So I decided to test my API like :</p>
  
  <pre><code>var request = require('supertest');
  
  ...
  
  describe('Routes', function () {
  
    var anAgent;
    var anotherAgent;
  
    before(function (done) {
      anAgent = request.agent(app);
      anotherAgent = request.agent(app);
  
      async.parallel([
        function (callback) {
          anAgent
            .post('/api/users/login')
            .send({user:user, password:password})
            .expect(200)
            .end(callback);
        },
        function (callback) {
          userAgent
            .post('/api/users/login')
            .send({user:anotherUser, password:anotherPassword})
            .expect(200)
            .end(callback);
        }
      ], done);
    });
  
    describe('/superroute', function () {
  
        it('should return the user', function (done) {
          anAgent
            .post('/api/superroute')
            .send(params)
            .expect(200)
            .end(function (err, res) {
              should.not.exist(err);
              res.body.err.should.equal('Super route');
              done();
            });
        });
  
        ...
   });
  
   ...
  
  });
  </code></pre>
  
  <p>The route <code>/superroute</code> is describe like </p>
  
  <pre><code>express.Router().post('/superroute', auth.ensureAuthenticated, superCtrl.superroute);
  </code></pre>
  
  <p>Where <code>ensureAuthenticated</code> middleware call the <code>req.isAuthenticated()</code> of passport.</p>
  
  <p>This API works fine when I use it from a simple angular front but when I run the test with mocha, the <code>passport.deserializeUser</code> method is not called and <code>isAuthenticated</code> return <code>false</code>. With the fact that the user is correctly logged and retrieved from the <code>/login</code> call, it's all I know.</p>
  
  <p>So the call returns 401 instead of 200.</p>
  
  <p>What can I've possibly missed ?</p>