javascriptnode.jstestingmocha.js

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.


Solution

  • 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.