Mocha

A guide for generating Trunk-compatible test reports for Mocha

You can automatically detect and manage flaky tests in your Mocha projects by integrating with Trunk. This document explains how to configure Mocha to output JUnit XML reports that can be uploaded to Trunk for analysis.

Checklist

By the end of this guide, you should achieve the following before proceeding to the next steps to configure your CI provider.

After correctly generating reports following the above steps, you'll be ready to move on to the next steps to configure uploads in CI.

Generating Reports

Before integrating with Trunk, you need to generate Trunk-compatible reports. For Mocha, the easiest approach is to generate XML reports.

First, install the mocha-junit-reporter package:

npm install --save-dev mocha-junit-reporter

You can then generate reports when you run your tests by providing the --reporter and --reporter-options options when you run your tests:

mocha --reporter mocha-junit-reporter --reporter-options mochaFile=./junit.xml

You can configure your Mocha runner to use the reporter programmatically as well:

var mocha = new Mocha({
    reporter: 'mocha-junit-reporter',
    reporterOptions: {
        mochaFile: './junit.xml'
    }
});

Report File Path

The resulting JUnit XML file will be written to the location specified by the mochaFile property in reporterOptions. In the examples above, the results would be at ./junit.xml.

Disable Retries

You need to disable automatic retries if you previously enabled them. Retries compromise the accurate detection of flaky tests.

You can disable retry by omitting the --retries CLI option and removing retries for individual tests.

Try It Locally

The Validate Command

You can validate your test reports using the Trunk CLI. If you don't have it installed already, you can install and run the validate command like this:

curl -fsSLO --retry 3 https://trunk.io/releases/trunk && chmod +x trunk
./trunk flakytests validate --junit-paths "./junit.xml"

This will not upload anything to Trunk. To improve detection accuracy, you should address all errors and warnings before proceeding to the next steps.

Test Upload

Before modifying your CI jobs to automatically upload test results to Trunk, try uploading a single test run manually.

You make an upload to Trunk using the following command:

curl -fsSLO --retry 3 https://trunk.io/releases/trunk && chmod +x trunk
./trunk flakytests upload --junit-paths "./junit.xml" \
    --org-url-slug <TRUNK_ORG_SLUG> \
    --token <TRUNK_ORG_TOKEN>

You can find your Trunk organization slug and token in the settings or by following these instructions. After your upload, you can verify that Trunk has received and processed it successfully in the Uploads tab. Warnings will be displayed if the report has issues.

Next Steps

Configure your CI to upload test runs to Trunk. Find the guides for your CI framework below:

Last updated