Mocha Integration with Mergify
Report your test results from Mocha to Mergify
This guide explains how to integrate Mocha with Test
Engine using the @mergifyio/mocha plugin. The plugin uploads your test
results to Test Engine when the run ends, with no JUnit file to write or
upload, and applies quarantine and
flaky detection inside the Mocha run. It takes up no
reporter, so Mocha’s output stays the one you read today.
If your CI uploads a JUnit report from Mocha today, see Moving from a JUnit upload.
Requirements
Section titled Requirements-
Node.js 22 or later in the job that runs the tests. Older versions are not supported: npm and pnpm only warn at install, Yarn 1 refuses.
-
Mocha 8.2 or later, the first with the global fixtures the plugin registers. On Mocha 8.2, run your tests serially: its own
--parallelmode crashes on current Node.js, with or without the plugin. On Node.js 26, use Mocha 10.6 or later: 8.3 to 10.5 crash on start. -
Mocha started from its command line, which loads the plugin through
--require. Code that runs Mocha through its API passes the plugin’s fixtures itself: see Running Mocha through its API. -
Mocha running in Node.js. Mocha in a browser (a page, Karma, web-test-runner, Cypress) is not supported. For Cypress, see the Cypress page.
Installation
Section titled InstallationInstall the @mergifyio/mocha
package alongside mocha to automatically upload your test results to Test
Engine.
Use the package manager version your project pins (packageManager in
package.json, mise.toml, .tool-versions), and check that the lockfile
diff only adds the new packages: another version rewrites unrelated entries
(older npm releases, for example, drop the libc fields of other packages;
npx npm@latest install … avoids it).
npm install --save-dev @mergifyio/mochayarn add --dev @mergifyio/mochapnpm add --save-dev @mergifyio/mochaConfiguration
Section titled ConfigurationHave Mocha require the plugin in your Mocha configuration file:
require: - '@mergifyio/mocha'With a JavaScript configuration:
module.exports = { require: ['@mergifyio/mocha'],};Or on the command line:
npx mocha --require @mergifyio/mochaIf your configuration already has a require list, add the plugin to it.
Mocha merges the require lists of its configuration and of its command line,
so a --require of your own keeps the plugin.
The plugin reports nothing, and says so, in watch mode and for a dry run
(--dry-run).
Running Mocha through its API
Section titled Running Mocha through its APICode that runs Mocha through its API instead of its command line does not read
--require. Pass the plugin’s fixtures yourself:
import { mergify } from '@mergifyio/mocha';import Mocha from 'mocha';
const { mochaGlobalSetup, mochaGlobalTeardown } = mergify();const mocha = new Mocha({ globalSetup: mochaGlobalSetup, globalTeardown: mochaGlobalTeardown });Mocha 12 is an ES module: import it, as above. Node.js 22’s require hands
it over as a namespace rather than as Mocha’s constructor.
Running in CI
Section titled Running in CIWhen the plugin reports
Section titled When the plugin reportsThe plugin uploads results only when the CI environment variable is set, or
when MERGIFY_CI_ENABLE is on. GitHub Actions, CircleCI and Buildkite set CI
for you. Jenkins does not: set CI=true, or MERGIFY_CI_ENABLE=true, in
the stage that runs your tests. If your tests behave differently when CI is
set (some test suites skip or add tests on CI), set MERGIFY_CI_ENABLE=true
instead of CI, so the tests that run stay the same.
CI counts as set unless it is empty or a false value (false, no, off,
0, f or n), so true, 1 and a CI system’s name (Woodpecker sets CI
to woodpecker) all count. MERGIFY_CI_ENABLE is stricter: only true,
yes, on, 1, t or y turn it on. Case does not matter for either.
Without a credential, the plugin uploads nothing and your tests run as usual, so pull requests from forks, which get neither an ID token nor secrets, report nothing and need no guard in the workflow.
Job names
Section titled Job namesEvery test is identified by its name and the name of the CI job that ran it. By default the job name is the job’s identifier in your CI:
| CI | Default job name |
|---|---|
| GitHub Actions | the job id (GITHUB_JOB), recorded with the workflow name (GITHUB_WORKFLOW) |
| CircleCI | CIRCLE_JOB, the expanded job name of each matrix leg |
| Buildkite | the step label (BUILDKITE_LABEL) |
| Jenkins | JOB_NAME, also used as the pipeline name, except in a multibranch pipeline (below) |
Set MERGIFY_TEST_JOB_NAME when that default is not one stable name per set of
tests:
-
GitHub Actions matrix: every leg shares one job id. Set it per leg from the matrix values, for example
MERGIFY_TEST_JOB_NAME: test (${{ matrix.python-version }}, ${{ matrix.os }}). -
Two test runs in one job: set a distinct name on each step.
-
Reusable workflows: a called workflow reports under the caller’s workflow name, so two called workflows whose jobs share an id (often
test) collide. Set a distinct name in each. -
Shards of one test suite are the same tests split across machines: give all shards the same name. Never put a shard index in it.
In a Jenkins multibranch pipeline, every branch and every pull request of the
project reports its tests under the same pipeline name and job name: the
multibranch project (my-repo, not my-repo/PR-123). MERGIFY_TEST_JOB_NAME
replaces the job name but never the pipeline name, so it cannot file the tests
of two Jenkins pipelines together. Inside a container, pass BRANCH_NAME
through as listed below, or the tests are filed under JOB_NAME.
Tests inside tox, Docker or Docker Compose
Section titled Tests inside tox, Docker or Docker Composetox, docker run and Docker Compose start the tests without the CI job’s
variables. Pass through CI or MERGIFY_CI_ENABLE, MERGIFY_TEST_JOB_NAME if
you set it, the credential (MERGIFY_TOKEN, or, on GitHub Actions with an ID
token, ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN),
and your CI’s variables: GITHUB_* and RUNNER_NAME, CIRCLECI and
CIRCLE_*, BUILDKITE*, or on Jenkins JENKINS_URL, BUILD_*, JOB_NAME,
BRANCH_NAME, NODE_NAME, GIT_*, CHANGE_* and TAG_NAME. tox’s
pass_env takes globs; docker run -e and Docker Compose need each name the
globs match in your job, except secrets such as GITHUB_TOKEN or
BUILDKITE_AGENT_ACCESS_TOKEN. Pass each variable by name, never by writing its
value into a file. In a container on GitHub Actions, also mount the file
GITHUB_EVENT_PATH points to, at the same path, or the run is recorded against
the merge commit.
Workflow linters
Section titled Workflow lintersWith an application key, zizmor can report
secrets-outside-env on the MERGIFY_TOKEN: ${{ secrets.MERGIFY_TOKEN }} line,
depending on its version and persona. Run the repository’s own zizmor
configuration on the changed workflow, and if it reports the finding, follow the
convention the repository already uses for it: a deployment environment on the
job, or an inline # zizmor: ignore[secrets-outside-env] comment.
Update your CI workflow
Section titled Update your CI workflowGitHub Actions
Section titled GitHub ActionsThe step that runs your tests needs nothing Mergify-specific:
- name: Run Tests 🧪 run: npx mochaLet your CI reach Mergify
Section titled Let your CI reach Mergify
Grant id-token: write to the job, or to the whole workflow. The job then trades its
GitHub-signed ID token for a Mergify OIDC CI token, and no MERGIFY_TOKEN is stored:
permissions: id-token: write # lets the job ask GitHub for an ID token contents: read # actions/checkout needs it
A permissions block sets every permission it does not list to none: list
the ones your other steps need too.
Mergify refuses the ID token until a trust policy of your organization matches the job. A
GitHub organization Owner or a CI Admin writes one under
Settings → Security & Access → CI Authentication → Trust Policies on the
dashboard. OIDC Authentication
covers trust policies, pull requests from forks and refused exchanges. If your workflows store
MERGIFY_TOKEN today,
move them off it.
Use an application key instead
Section titled Use an application key instead
Other CIs authenticate with a ci application key, and so do the GitHub Actions
jobs OIDC leaves out: runs for pull requests from forks when your organization sends them
secrets, and jobs that send scopes from the base branch (pull_request_target,
workflow_run, issue_comment). Store the key as the
MERGIFY_TOKEN repository secret and set it on the job:
env: MERGIFY_TOKEN: ${{ secrets.MERGIFY_TOKEN }}
A MERGIFY_TOKEN that is set wins over the ID token. For pull requests from forks,
set it on those runs only and drop the fork condition from the upload step, as
Jobs that keep a key shows. Store the key in
your
Dependabot secrets too, since runs for Dependabot pull requests read only those.
Buildkite
Section titled BuildkiteSet MERGIFY_TOKEN to a ci application key in the
environment of the agents running your tests.
The step itself then needs no Mergify-specific configuration:
steps: - label: "Run Tests 🧪" command: npx mochaThe plugin automatically collects your test results and sends them to Test Engine.
Quarantine and crashed runs
Section titled Quarantine and crashed runsBefore any test runs, the plugin fetches the list of tests
quarantined in Test Engine. When one of them fails,
Mocha counts it as passed: it does not fail your run or stop it under
--bail, and your reporter shows it passed. The test reaches Test Engine as
failed and quarantined. This works the same whether Mocha runs your files in
its main process or in its workers (--parallel). Once the run is over, the
Mergify Test Engine section says what the quarantine did.
A failing hook does not fail your run when
every test it kept from running is quarantined. A
failing after hook keeps no test from running, so quarantine never covers it.
The exit code of your test step already accounts for quarantine, so the step needs nothing more:
-
Do not add
continue-on-error: true. The recipes that upload a JUnit report with themergifyio/gha-mergify-ciaction need it because the action decides the job’s result after the tests. Here nothing does, so it would let every real failure through. -
There is no step
idto set and notest_step_outcometo pass: both belong to that action, which this setup does not use.
A crash cannot pass for a green run either. An error no test raised still makes Mocha exit non-zero and fail the step, and so does Mocha dying mid-run. The plugin uploads results when the run ends, so a process killed outright before then, such as by the out-of-memory killer, sends nothing to Test Engine.
If the plugin cannot fetch the quarantine list, it quarantines nothing for that run, and a quarantined test that fails makes the step fail as usual.
What reaches Test Engine
Section titled What reaches Test EngineEvery test of the run reaches Test Engine as it ended: passed, failed with its error, or skipped.
A failing hook can keep tests from running, and Mocha reports only the hook. The plugin reports each test the hook kept from running as failed, with the hook’s error.
A test that Mocha’s retries ran again reaches Test Engine as its first run,
with how it ended and what it raised. Every run after it is counted, and the
test’s duration covers them all.
Flaky detection
Section titled Flaky detectionThe plugin reruns tests within the budgets set under Native Flaky Detection:
-
On a pull request, a test the target branch does not have yet is new. The plugin runs it again right after its own run, as many times as fit in the Prevention Budget. When one of those runs fails, the test is flaky: Mocha reports it failed, with that run’s error, so the pull request does not merge. See Prevention.
-
On a push, the plugin reruns the tests Test Engine knows as unhealthy, within the Detection Budget, to report whether they still are. The run’s result does not change. See Rerunning unhealthy tests.
The runs Mocha’s retries made of a new test count too: a new test that
retries rescued is flaky, and Mocha reports it failed with its first run’s
error. Those runs do not use up the budget. Your reporter hears of no rerun,
and Mocha’s retries do not apply to the reruns. The Mergify Test Engine
section says what they found.
In a parallel run (--parallel), the reruns wait until the run’s tests are
over. Then, before Mocha’s global teardown, Mocha’s workers run again in full
each file that holds a test to rerun, and run that test as many times as fit.
Your reporter has printed the run by then, so it shows a flaky new test as
passed: the Mergify Test Engine section names it, and the run fails. A
parallel run that --bail stopped reruns nothing.
Test names
Section titled Test namesEach test reaches Test Engine named by its file, relative to the directory
Mocha runs in, the describe blocks around it, and its own title:
test/api.spec.js > users > creates oneTest Engine tracks a test’s history under that name, so renaming the file, a
describe block or the test starts a new test.
Matrix runs
Section titled Matrix runsEvery leg of a GitHub Actions matrix shares one job name, which is
part of a test’s identity
in Test Engine, so the legs’ results merge into one test. Set
MERGIFY_TEST_JOB_NAME on each leg and include the matrix value, so each leg
reports under its own name:
jobs: test: runs-on: ubuntu-latest permissions: id-token: write contents: read strategy: matrix: node-version: [22, 24] steps: # ... - name: Run Tests 🧪 env: MERGIFY_TEST_JOB_NAME: test (node ${{ matrix.node-version }}) run: npx mochaSetting MERGIFY_TEST_JOB_NAME on a job that already reports changes its
name, so its tests start a new history in Test Engine.
Moving from a JUnit upload
Section titled Moving from a JUnit uploadIf your CI writes a JUnit report with Mocha’s xunit reporter or
mocha-junit-reporter and uploads it with the mergifyio/gha-mergify-ci
action, the mergifyio/mergify-ci Buildkite plugin or
mergify ci junit-process, switch to @mergifyio/mocha:
-
Install
@mergifyio/mochaand add it to Mocha’srequire, as shown in Configuration. -
Keep your reporter if another tool still reads the JUnit file. Otherwise, go back to the reporter you read in your terminal: the plugin needs none.
-
Remove the upload: the
mergifyio/gha-mergify-cistep, themergifyio/mergify-ciplugin on the Buildkite step, or themergify ci junit-processcommand.@mergifyio/mochasends the results itself. If you ranmergify ci junit-process, also drop|| exit_code=$?from your test command, so its exit code is the step’s again. -
On GitHub Actions, remove
continue-on-error: truefrom the test step. If you added a step for pull requests from forks that fails the job when no report was uploaded, remove it too. -
If your upload set a
job_name, as a matrix setup does, move its value toMERGIFY_TEST_JOB_NAMEon the step that runs the tests, as shown in Matrix runs, so your tests keep the job name they report under. -
Grant the job
id-token: write, or move the upload’stokentoMERGIFY_TOKENon the job, as shown in Update your CI workflow.
What changes in Test Engine once the plugin uploads:
-
Your tests get new names, so their history starts again under those names.
-
Quarantine entries made from your JUnit uploads still apply when the upload named a test the way
xunitdoes, or the waymocha-junit-reporterdoes with its default options. -
Flaky detection judges whether a test is new by its name. Until your target branch has run with the plugin, every test is new to it, so a pull request reruns its tests within the Prevention Budget and a test that was already flaky can fail the job as a new flaky test.
Verify and review in Test Engine
Section titled Verify and review in Test EngineAfter pushing these changes, your next CI run reports its Mocha results automatically.
You can then review your test results, including any failures or flaky tests, directly in the Test Engine dashboard.
Environment variables
Section titled Environment variables| Variable | Purpose |
|---|---|
MERGIFY_API_URL |
Base URL of the Mergify API. An API URL given on the command line or in a reporter's configuration takes precedence. |
MERGIFY_CI_DEBUG |
Set to |
MERGIFY_CI_ENABLE |
Set to |
MERGIFY_FAIL_FIRST_ENABLE |
Set to |
MERGIFY_TEST_JOB_NAME |
Name the job's test results are reported under, instead of the CI job's own name. Set one per environment, never per shard: a name per shard splits a test's history. |
MERGIFY_TEST_RETRY_ENABLE |
Set to |
MERGIFY_TOKEN |
The Mergify credential: an application key in CI. A GitHub Actions job granted |
MERGIFY_TRACEPARENT |
W3C |
To check the setup without uploading anything, run your tests with
MERGIFY_CI_ENABLE=true MERGIFY_CI_DEBUG=true: the plugin prints the spans it
would send.
Was this page helpful?
Thanks for your feedback!