Can't set headers after they are sent error while trying to maintain user session for a test with chai request agent
<p>We are currently struggling with a <code>Uncaught Error: Can't set headers after they are sent.</code> error message when trying to chain a user sign in into a test with chai-http.</p>

<p>The test signs in as a user which already exists in the database via our API and then should attempts to GET all items from an existing route. Our current test is below which mirrors very closely the example given on the Chai-HTTP documentation <a href="http://chaijs.com/plugins/chai-http/#retaining-cookies-with-each-request" rel="nofollow">http://chaijs.com/plugins/chai-http/#retaining-cookies-with-each-request</a>.</p>

<pre><code>it('should return all notes on /api/notes GET', function (done) {
agent
  .post('/users/register')
  .send(user)
  .then(function() {
    return agent
      .get('/api/notes')
      .end(function (err, res) {
        // expectations
        done();
      });
  });
});
</code></pre>

<p>Our stack trace</p>

<pre><code> Uncaught Error: Can't set headers after they are sent.
  at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
  at ServerResponse.header (node_modules/express/lib/response.js:718:10)
  at ServerResponse.send (node_modules/express/lib/response.js:163:12)
  at ServerResponse.json (node_modules/express/lib/response.js:249:15)
  at app/routes/usersRouter.js:16:29
  at node_modules/passport/lib/middleware/authenticate.js:236:29
  at node_modules/passport/lib/http/request.js:51:48
  at pass (node_modules/passport/lib/authenticator.js:287:14)
  at Authenticator.serializeUser (node_modules/passport/lib/authenticator.js:289:5)
  at IncomingMessage.req.login.req.logIn (node_modules/passport/lib/http/request.js:50:29)
  at Strategy.strategy.success (node_modules/passport/lib/middleware/authenticate.js:235:13)
  at verified (node_modules/passport-local/lib/strategy.js:83:10)
  at InternalFieldObject.ondone (node_modules/passport-local-mongoose/lib/passport-local-mongoose.js:149:24)
</code></pre>

<p>This is the function being called on our users router which seems to be raising the error (not raised manually, just raised when using chai)</p>

<pre><code>router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username }), req.body.password, function(err, user) {
    if (err) {
      res.status(500).json({info: err});
    }

    passport.authenticate('local')(req, res, function () {
        res.status(200).json({info: "success"});
    });
});
});
</code></pre>

<p>Manually testing this functionality works correctly, the issue seems to purely be down to our test and how it is interacting with passport.</p>

<p>Does anyone have any suggestions or pointers which could be of help?</p>