title: Run Mocha programmatically and pass results to variable or function
body: <p>I've setup a suite of tests in mocha using ZombieJS and Chai. The tests load up a website and check if various services are booked in correctly and are displaying to visitors of the website.</p>
  
  <p>What I'm aiming for is that the tests will run daily and then email the results to my team. The tests are all running as expected but the blockage I've hit is the following.</p>
  
  <p>How do I pass the JSON reporter results to another node.js script where I can email the results. Building the email and sending it is going to be straight forward using nodemailer and underscore templating.</p>
  
  <p>My current thinking is there are two approaches. Run the mocha test with a shell script and pipe the JSON output to a node script and process the JSON from a  command line argument. Something like...</p>
  
  <pre><code>mocha test/services/homepage.js &gt; node email.js
  </code></pre>
  
  <p>The other alternative is to run the tests from within a node script and get the returned result in a variable. I've been using information from here to run the tests within node.</p>
  
  <p><a href="https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically" rel="noreferrer">https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically</a></p>
  
  <p>This runs correctly but I'm lost with how to get the JSON reporter results into a variable from the below code.</p>
  
  <pre><code>var Mocha = require('mocha'),
      Suite = Mocha.Suite,
      Runner = Mocha.Runner,
      Test = Mocha.Test;
  
  // First, you need to instantiate a Mocha instance
  
  var mocha = new Mocha({
      reporter: 'json'
  });
  
  var suite = new Suite('JSON suite', 'root');
  var runner = new Runner(suite);
  var mochaReporter = new mocha._reporter(runner);
  
  mocha.addFile(
      '/Users/dominic/Git/testing-rig/test/services/homepage.js'
  );
  
  runner.run(function(failures) {
      // the json reporter gets a testResults JSON object on end
      var testResults = mochaReporter.testResults;
  
      console.log(testResults);
      // send your email here
  });
  </code></pre>