Mocha
In this tutorial, we'll start with a JavaScript NodeJS project that has an existing Mocha test suite, and we'll add JUnit XML as an additional output format for the test suite. JUnit XML contains data such as passed and failed tests, suitenames, test files, filenames, test cases, and error messages helpful for debugging. In each step in this doc, we'll show the Git diff for the change that we're making.
Add
mocha-junit-reporterandmocha-multi-reportersas development dependencies (no need for custom reporters!).npm install --save-dev mocha-junit-reporter mocha-multi-reportersVerify that your package.json file includes these new dependencies:
"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"
}
}Create a
mocha-reporter-config.jsonfile and configure it to enable the spec reporter (which is the default Mocha reporter) and the mocha-junit-reporter as a parameter after the spec default reporter.+{
+ "reporterEnabled": "spec, mocha-junit-reporter"
+}Update your CI workflow to use
mocha-multi-reportersas the test reporter plugin. Here we updatenpm testto use the new reporter configuration that we set up above, with inline reporter-options output.jobs:
- run: npm ci
- - run: npm test
+ - run: npm test -- --reporter mocha-multi-reporters --reporter-options configFile=mocha-reporter-config.jsonThis 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.ymlfor CircleCI, etc.).By default,
mocha-junit-reporterexports the report to a file namedtest-results.xmlat the root of your project. Add that to your.gitignorefile so that it doesn't accidentally get checked into the repository./node_modules
+/test-results.xmlCommit these changes to your repository using the git command line tool.
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 - or view the README for setup repository instructions.
When you run tests or your test script, you should now see generated junit xml files (with tests failed and passed) in your test reports directory for MochaJS - the first step in detecting flaky tests.