Skip to main content

Mocha

In the steps below, we'll start with a JavaScript project that has an existing Mocha test suite, and we'll add JUnit XML as an additional output format for the test suite. In each step, we'll show the Git diff for the change that we're making.

  1. Add mocha-junit-reporter and mocha-multi-reporters as development dependencies.
npm install --save-dev mocha-junit-reporter mocha-multi-reporters

Verify that your package.json file includes these new dependencies:

@@ -13,6 +13,8 @@
"author": "Richard Hendricks",
"license": "MIT",
"devDependencies": {
- "mocha": "^9.1.1"
+ "mocha": "^9.1.1",
+ "mocha-junit-reporter": "^2.0.0",
+ "mocha-multi-reporters": "^1.5.1"
}
}

2. Create a mocha-reporter-config.json file and configure it to enable the spec reporter (which is the default Mocha reporter) and the mocha-junit-reporter.

@@ -0,0 +1,3 @@
+{
+ "reporterEnabled": "spec, mocha-junit-reporter"
+}

3. Update your CI workflow to use mocha-multi-reporters as the test reporter.

Here we update npm test to use the new reporter configuration that we set up above.

@@ -18,4 +18,4 @@ jobs:

- run: npm ci

- - run: npm test
+ - run: npm test -- --reporter mocha-multi-reporters --reporter-options configFile=mocha-reporter-config.json

This example project uses Github Actions for CI, so we're updating our CI script in the .github/workflows/ directory. If you're using a different CI service, apply the same change wherever your CI script is defined (e.g., .circleci/config.yml for CircleCI, etc.).

4. By default, mocha-junit-reporter writes the report to a file named test-results.xml at the root of your project.

Add that to your .gitignore file so that it doesn't accidentally get checked into the repository.

@@ -1 +1,2 @@
/node_modules
+/test-results.xml

5. Commit these changes to your repository.

git commit -am "Update CI to generate JUnit XML for test results"

The final result of these changes should resemble commit 30e6cef in the buildpulse-example-mocha repository.