title: Testing asynchronous function with mocha
body: <p>I want to test a asynchronous javascript function that runs in node.js and makes a simple request to a http api:</p>
  
  <pre><code>const HOST = 'localhost';
  const PORT = 80;
  
  http = require('http');
  
  var options = {
      host: HOST,
      port: PORT,
      path: '/api/getUser/?userCookieId=26cf7a34c0b91335fbb701f35d118c4c32566bce',
      method: 'GET'
  };
  doRequest(options, myCallback);
  
  function doRequest(options, callback) {
  
      var protocol = options.port == 443 ? https : http;
      var req = protocol.request(options, function(res) {
  
          var output = '';
          res.setEncoding('utf8');
  
          res.on('data', function(chunk) {
              console.log(chunk);
              output += chunk;
          });
  
          res.on('error', function(err) {
              throw err;
          });
  
          res.on('end', function() {
              var dataRes = JSON.parse(output);
              if(res.statusCode != 200) {
                  throw new Error('error: ' + res.statusCode);
              } else {
                  try {
                      callback(dataRes);                        
                  } catch(err) {
                      throw err;
                  }
              }
          });
  
      });
  
      req.on('error', function(err) {
          throw err;
      });
  
      req.end();
  
  }
  
  function myCallback(dataRes) {
      console.log(dataRes);
  }
  </code></pre>
  
  <p>Executed this code works and the response will be displayed as expected.</p>
  
  <p>If I execute this in a mocha test the request is not executed:</p>
  
  <pre><code>describe('api', function() {
      it('should load a user', function() {
          assert.doesNotThrow(function() {
              doRequest(options, myCallback, function(err) {
                  if (err) throw err;
                  done();
              });
          });
          assert.equal(res, '{Object ... }');
      });
  });
  </code></pre>
  
  <p>The Problem is, that no code after:</p>
  
  <pre><code>var req = protocol.request(options, function(res) {
  </code></pre>
  
  <p>is executed not even a simple console.log.</p>
  
  <p>Can anybody help?</p>