Mocha Integration with Mergify
Report your test results from Mocha tests to Mergify
This guide shows how to generate JUnit reports from your Mocha tests and upload them to Test Engine using your CI workflow.
Generate a JUnit report with Mocha
Section titled Generate a JUnit report with MochaMocha can write a JUnit XML report with either of two reporters:
-
xunitships with Mocha. It needs no extra package and works on Mocha 11 and Mocha 12, including in--parallelmode. -
mocha-junit-reporteris the most widely used third-party JUnit reporter. As of version 2.2.1, it crashes on Mocha 12 and in--parallelmode, so it only suits Mocha 11 or earlier running tests serially.
For a new setup, or if you run Mocha 12 or --parallel, use xunit. If your
project already uses mocha-junit-reporter, you can keep it and set the
options below.
Using the built-in xunit reporter
Section titled Using the built-in xunit reporterSet the reporter and its output file in your .mocharc.yml:
reporter: xunitreporter-option: - output=junit.xmlOr pass them on the command line:
npx mocha --reporter xunit --reporter-option output=junit.xmlWith output set, xunit writes the report to that file and prints nothing to
your terminal. To keep Mocha’s usual output as well, see
Keeping your terminal output.
Using mocha-junit-reporter
Section titled Using mocha-junit-reporterFirst, install the reporter:
npm install --save-dev mocha-junit-reporterThen set it in your .mocharc.yml:
reporter: mocha-junit-reporterreporter-option: - mochaFile=junit.xml - jenkinsMode=true - 'suiteTitleSeparatedBy= ' - includePending=trueOr pass the same options on the command line:
npx mocha --reporter mocha-junit-reporter \ --reporter-option "mochaFile=junit.xml,jenkinsMode=true,suiteTitleSeparatedBy= ,includePending=true"These options do the following:
-
mochaFilesets the report’s path. Without it, the reporter writestest-results.xml. -
jenkinsModewrites the test’sdescribetitles toclassnameand its own title toname. -
suiteTitleSeparatedBy, set to a single space, joins thosedescribetitles the wayxunitdoes, so both reporters give a test the same name. See Test names in Test Engine for how Test Engine builds that name. -
includePendingreports skipped tests. By default, the reporter leaves them out of the file.
Keeping your terminal output
Section titled Keeping your terminal outputMocha runs a single reporter, so pointing it at a JUnit reporter replaces the
output you usually read in your terminal or CI logs. To get both, run them
through mocha-multi-reporters:
npm install --save-dev mocha-multi-reportersCreate a reporter-config.json that lists the reporters to run. The JUnit
reporter’s options go under a key named after it. For xunit:
{ "reporterEnabled": "spec, xunit", "xunitReporterOptions": { "output": "junit.xml" }}For mocha-junit-reporter:
{ "reporterEnabled": "spec, mocha-junit-reporter", "mochaJunitReporterReporterOptions": { "mochaFile": "junit.xml", "jenkinsMode": true, "suiteTitleSeparatedBy": " ", "includePending": true }}Replace spec with the reporter you use today, then point Mocha at the
configuration file in your .mocharc.yml:
reporter: mocha-multi-reportersreporter-option: - configFile=reporter-config.jsonTest names in Test Engine
Section titled Test names in Test EngineTest Engine names each test from the classname and name attributes of its
<testcase> element, joined with a dot: <classname>.<name>. When classname
is empty, the test is named <name> alone. Test Engine tracks a test’s history
under that name, and quarantine matches failures
against it.
The two reporters fill these attributes differently. Take this test:
describe('Cart', function () { describe('#add()', function () { it('adds an item', function () { // ... }); });});| Attribute | xunit | mocha-junit-reporter, default options | mocha-junit-reporter, options above |
|---|---|---|---|
classname | Cart #add() | adds an item | Cart #add() |
name | adds an item | Cart #add() adds an item | adds an item |
| Test Engine name | Cart #add().adds an item | adds an item.Cart #add() adds an item | Cart #add().adds an item |
By default, mocha-junit-reporter writes the test’s own title to classname
and its full title to name, so the name in Test Engine starts with the test’s
title and then repeats it. Setting testCaseSwitchClassnameAndName on its own
swaps the two attributes but still repeats the title. jenkinsMode writes the
describe titles to classname instead, joined with a dot unless you set
suiteTitleSeparatedBy. With a space, both reporters give every test the same
name, so you can move from mocha-junit-reporter to xunit later, for
example when you upgrade to Mocha 12, and keep each test’s history and
quarantine.
Because a test’s name is built from its describe and it titles:
-
Renaming a test or one of its
describeblocks makes it a new test in Test Engine, and a quarantine set on the old name no longer applies. -
Keep values that change between runs, such as timestamps, random IDs or generated data, out of titles. Otherwise each run reports a different test.
-
Give each test a unique title within its
describeblock. Two tests with the same full title share one name, and their results merge. -
A test outside any
describeblock is named by its title alone.
Update your CI workflow
Section titled Update your CI workflowGitHub Actions
Section titled GitHub ActionsAfter generating the JUnit report, add a step to upload the results to Test
Engine using the mergifyio/gha-mergify-ci action.
With the reporter set in .mocharc.yml, run Mocha as usual. For example, in
your workflow file:
- name: Run Mocha Tests and Generate JUnit Report id: tests continue-on-error: true run: npx mocha- name: Mergify CI Upload if: success() || failure() uses: mergifyio/gha-mergify-ci@v27 with: token: ${{ secrets.MERGIFY_TOKEN }} report_path: junit.xml test_step_outcome: ${{ steps.tests.outcome }}Key Points:
-
if: success() || failure(): Runs the upload step even if tests fail, ensuring Test Engine has the full report. -
report_path: junit.xml: Points to where your JUnit file is located. Make sure it matches the path you set in your CI job. -
test_step_outcome: ${{ steps.tests.outcome }}: Passes the test runner step's outcome so Mergify can detect silent failures where the runner crashed but the JUnit report appears clean. Add anid(such astests) to your test runner step and update thesteps.<id>.outcomereference to match.
If you use a job matrix in your workflow (e.g., to test across multiple versions), every leg
reports the same job name, because GitHub Actions gives them all one GITHUB_JOB. Set
the job_name input so Test Engine can tell the reports apart:
jobs: example_matrix: strategy: matrix: version: [10, 12, 14]Your upload step should look like:
- name: Mergify CI Upload if: success() || failure() uses: mergifyio/gha-mergify-ci@v27 with: job_name: example_matrix (${{ matrix.version }}) token: ${{ secrets.MERGIFY_TOKEN }} report_path: junit.xml test_step_outcome: ${{ steps.tests.outcome }}To benefit from Test Engine Quarantine, you need to add continue-on-error: true
in your GitHub Actions step that executes your tests and generates the JUnit file.
The step running the gha-mergify-ci action will determine the success or failure conclusion,
considering quarantined tests.
You should also pass test_step_outcome: ${{ steps.tests.outcome }} to the step that runs
mergifyio/gha-mergify-ci (where tests is the id of your test runner step) to detect
silent failures where the test runner crashed but the JUnit report appears clean. Without
this input, a crash that produces a partial or empty report could be mistakenly treated as a
success.
Buildkite
Section titled Buildkitesteps: - label: "Run tests" command: <your test command> plugins: - mergifyio/mergify-ci#v8: action: junit-process report_path: junit.xmlKey Points:
-
The plugin runs in the
post-commandhook, so it uploads results after your tests finish, even if they fail. -
report_path: junit.xml: Points to where your JUnit file is located. Make sure it matches the path you set in your test configuration. - Silent failure detection is automatic: the plugin reads the step's exit code to detect cases where the test runner crashed but the JUnit report appears clean.
If you use a build matrix in your pipeline, each variation reports its own step label as its job
name, so the variations are already distinct. Set the job_name plugin property when the
label is not the name you want Test Engine to file the reports under:
steps: - label: "Flaky detection ({{matrix}})" matrix: - "3.10" - "3.11" - "3.12" command: <your test command> plugins: - mergifyio/mergify-ci#v8: action: junit-process job_name: "Tests ({{matrix}})" report_path: junit.xmlWhen using the Buildkite plugin for Test Engine Quarantine, the plugin automatically detects test failures using the step’s exit code. No extra configuration is needed.
The mergifyio/mergify-ci plugin runs in the post-command hook and reads
BUILDKITE_COMMAND_EXIT_STATUS to detect silent failures where the test runner
crashed but the JUnit report appears clean.
Any CI (Mergify CLI)
Section titled Any CI (Mergify CLI)
Install the Mergify CLI in your pipeline and export
MERGIFY_TOKEN. Run
mergify ci junit-process after your tests:
set -o pipefailnpx mochaexit_code=$?mergify ci junit-process \ --test-exit-code "$exit_code" \ junit.xmlKey Points:
-
MERGIFY_TOKEN: Export this environment variable with your Mergify application key sojunit-processcan authenticate to the API. -
--test-exit-code "$exit_code": Passes the test runner's exit code so Mergify can detect silent failures where the runner crashed but the JUnit report appears clean. -
junit-processexits last, so its status becomes the step's. Quarantine depends on that: it exits0when every failure it found is quarantined, and1when one is not. Re-exiting with the test runner's own code would fail the step whatever quarantine decided. -
The branch quarantine is evaluated against is detected from your CI provider, falling back to
the checked-out branch. Pass
--tests-target-branch <branch>only to override it.
Verify and review in Test Engine
Section titled Verify and review in Test EngineAfter pushing these changes:
- Your GitHub Actions workflow will execute your Mocha tests.
- A JUnit report (
junit.xml) is generated. - The Mergify CI action uploads the report to Test Engine.
You can then review your test results, including any failures or flaky tests, directly in the Test Engine dashboard.
Troubleshooting tips
Section titled Troubleshooting tipsMocha 12: If the run ends with
TypeError: Class constructor Base cannot be invoked without 'new', your version ofmocha-junit-reporterdoes not support Mocha 12. Switch to thexunitreporter.Parallel mode: If
mocha-junit-reporterfails withTypeError: Cannot read properties of undefined (reading 'testsuite')when you run with--parallel, switch to thexunitreporter or run your tests serially.No output in the terminal: The
xunitreporter prints nothing onceoutputis set. Usemocha-multi-reportersto keep your usual reporter, as shown in Keeping your terminal output.- The CLI provides information about the upload. Check the logs in GitHub Actions.
- File Paths: Double-check that the output file matches the path used in
report_path. - Permissions: Make sure the
MERGIFY_TOKENis valid and setup in your GitHub Actions secrets as explained in the docs. - Workflow Conditions: If your step is not running, confirm the if condition is actually triggered in your job.
Was this page helpful?
Thanks for your feedback!