title: Node.js - Unit Testing Middleware
body: <p>I have an api with a middleware function which I use to filter incoming requests. The functions checks the present of a <em>token</em> in the header, then makes two calls to the database, one to check the token and one to get some information and pass it on to the request object, if the 1st call was successful.</p>
  
  <p>I am struggling to understand how to unit test this functions, by mocking up the request object and also the database calls.</p>
  
  <p><strong>middleware.js</strong></p>
  
  <pre><code>exports.checkToken = function (req, res, next) {
    if (!req.get('token')) {
        return res.status(400).json('Bad request');
    }
  
    var token = req.get('token'); //get token from the header 
  
    User.findOne({'token': token}, function(err, user) {
        // skipped error checking or no user found
        Account.findOne({'_id': user.account}, function(err, account) {
            // skipped error checking or no account found
            req.somevalue = account;
            return next();
        });
    });
  };
  </code></pre>
  
  <p>Currently I am using <strong>mocha</strong>, <strong>chai</strong> and <strong>sinon</strong> and was thinking of the following:</p>
  
  <ul>
  <li><p>mock User.findOne and Account.findOne using sinon.stub()</p></li>
  <li><p>not really sure what to do about the req, res and next objects. How to emulate these?</p></li>
  </ul>