title: Why does Mocha exit before a reporter is done handling a test failure?
body: <p>I'm writing a test suite using PhantomJS (via <a href="https://npmjs.org/package/selenium-webdriver" rel="nofollow"><code>selenium-webdriver</code></a>) and Mocha. For reporting I need a screenshot every time a test fails and so I've written a custom reporter for Mocha based on <code>spec</code> reporter:</p>
  
  <pre><code>module.exports = Screenshot;
  
  var Spec = require('mocha/lib/reporters/spec');
  var fs = require('fs');
  
  // custom library generating PhantomJS instances
  var phantoms = require("phantoms"); 
  
  function Screenshot(runner) {
      Spec.call(this, runner);
  
      runner.on('fail', function(test, err){
          var driver = phantoms.getDriver();
  
          driver.getCurrentUrl().then(function(url) {
              console.log(url);
          });
  
          console.log('This works');    
  
          driver.takeScreenshot().then(function(img) {
              console.log("Writing screenshot");
              fs.writeFileSync("/tmp/selenium.png", img, 'base64');
              return "/tmp/selenium.png";
          });
  
          console.log('This also works');    
  
      });
  }
  
  Screenshot.prototype.__proto__ = Spec.prototype;
  </code></pre>
  
  <p>Now I have a funny situation when a test fails: Mocha does everything synchronous from the hook callback (e.g. both logging statements), however neither the <code>getCurrentUrl</code> promise nor the one for <code>takeScreenshot</code> gets resolved, which is obviously not what I expected.</p>
  
  <p>However, I've found out that if I throw an exception after those promises are defined (e.g. after <code>driver.takeScreenshot()</code>), Mocha terminates immediately without either a proper report or an error message (OK so far, even though I'd prefer getting a "Reporter raised an unexpected exception" message), but resolves both WebDriver promises, so that a screenshot is taken and also the current URL is printed just before the exit.</p>
  
  <p>I'm playing with a small test suite of a couple of tests only, so I assumed that maybe Mocha considers the hook done and returns to OS before promises have a chance to be resolved. Is there an another explanation? Am I at fault here or is it Mocha? How do I fix this properly?</p>
  
  <p>PS: It's perfectly possible that <code>selenium-webdriver</code> and its promises framework is at fault here. However, I don't want to place blame, but find a solution and I'm happy about any explanation to this phenomenon.</p>