J. Toming
J. Toming

Reputation: 91

Get all test fails from Mocha

I have about 600 tests made with Mocha and now I need to automatically run all of them and get all errors and success count to send this information to monitoring server.

I can make bash script, which runs tests and writes Mocha log to file, then parse this log file and get success count and fail logs (for example by grep), but this is too dirty solution.

I would prefer run tests programmatically and get from Mocha something like fail messages and success tests array to work around this, but I couldn't find any docs about this.

Upvotes: 5

Views: 2014

Answers (2)

Abhinav Saini
Abhinav Saini

Reputation: 298

Update from future (2025):

You can simply generate the mocha report as JSON, which will include all the failed and successful ones (even the file name and titles of failing/successful cases - and not just their count).

mocha --reporter=json --reporter-option output=filesData.json testCases.js

You can then read this JSON output and do the needful (eg. exporting to monitoring server)

Upvotes: 0

Laurynas Lubys
Laurynas Lubys

Reputation: 236

Create a file, let's say intercept-failures.js with the following content:

const failures = [];
const successes = [];

afterEach(function () {
    const title = this.currentTest.title;
    const state = this.currentTest.state;
    if (state === "passed") {
        successes.push(title)
    } else if (state === "failed") {
        failures.push(title)
    }
});

after(function () {
    console.log("failures", failures);
    console.log("successes", successes);
});

Add a flag --file intercept-failures.js to your mocha invocation (for example mocha --file intercept-failures.js test/**)

The afterEach hook accumulates all test results, and then you can do something with them in the after hook. The --file flag just makes sure that the hooks are added to all test suites.

Upvotes: 9

Related Questions