Mocha

April 30, 2024

What is Mocha?

Mocha is a test automation framework for Javascript and Typescript.  Jest is generally used for unit testing, meaning it tests parts of a codebase in isolation, rather than integration testing where the parts are combined and tested to see how they work together (though Mocha can be used for both). Mocha makes it easy to write and manage standardized Javascript tests for your codebase. Mocha works hand in hand with your CI (Continuous Integration) system to ensure tests are reliable and repeatable across team members and environments.

Enabling XML Output

Mocha can be configured to produce JUnit XML output by adding the mocha-junit-reporter  package to your codebase.

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

Now run Mocha from the command line or inside your CI system as:

1mocha test --reporter mocha-junit-reporter

Test Suite naming

The mocha-junit-reporter will automatically fill in values for the <testcase> and <testsuite> name and class attributes. The test:

1describe('addition', () => {
2  describe('positive numbers', () => {
3    it('should add up', () => {
4      expect(1 + 2).toBe(3);
5    });
6  });
7});

will produce output that looks like this:

1<testsuites name="Mocha Tests">
2  <testsuite name="addition">
3    <testcase classname="addition positive numbers should add up" 
4              name="addition positive numbers should add up"
5              file="/somepath/tests/mocha/mocha.test.js"
6              >
7    </testcase>
8  </testsuite>
9</testsuites>

The default attributes can be configured with the reporterOptions argument in the .mocharc.js or similar config file.

1var mocha = new Mocha({
2    reporter: 'mocha-junit-reporter',
3    reporterOptions: {
4        testsuitesTitle: true,
5        // suites separator, default is space (' ')
6        suiteTitleSeparatedBy: '.' 
7    }
8});

By default Mocha will include the file attribute.

Handling Retries

By default, Mocha will not retry tests. The developer must restart the tests manually.  To have Mocha automatically retry failed tests use the retries() setting. Ex:

1describe('retries', () => {
2 this.retries(4)
3 test('will fail', () => {
4   expect(true).toBe(false);
5 });
6})

If you need to retry a lot of tests that is a strong indicator that you may have flaky tests. These are tests that sometimes pass and sometimes fail, slowing down your development process. You can get early access to Trunk’s new Flaky Tests tool to manage these types of tests better.

Other Configuration

See an example of MochaJS invoked form a GitHub action here.

Try it yourself or
request a demo

Get started for free

Try it yourself or
Request a Demo

Free for first 5 users