Using multiple mocha reporters

Mocha, the “simple, flexible and fun” JavaScript test framework provides several built-in reporters. By default you can only use 1 but there may be situations where you want to use several, for example you’d like the test report to be both visible in the build log and also available in XML form ala JUnit. Luckily, you can combine these.

To do this:

  1. Install the following npm packages in your project:
    • mocha
    • mocha-junit-reporter
    • mocha-multi-reporters
  2. Create a config folder with a mocha-config.json file in it:
    {
     "reporterEnabled": "list,mocha-junit-reporter",
     "mochaJunitReporterReporterOptions": {
         "mochaFile": "testResults/results.xml"
     }
    }
    

    list is one of the built-in reporters in mocha. mochaFile is where the test results will be generated into (if the file/folder does not exist, it will be).

  3. In your npm test command (or if using a custom command, e.g. npm run unit-tests) mention the following, e.g.:

    "scripts": { 
     "test": "mocha --recursive --reporter mocha-multi-reporters --reporter-options configFile=config/mocha-config.json"
    }
    

    Note that by default mocha will look for a test folder at the root of the project. If you have a folder named differently or want mocha to look at a specific folder, be sure to state this explicitly: mocha test/unit-tests.