Mocha: Hide console.log output from successful tests

console.log, mocha.js, node.js

Solution

You can modify the `console.log` function to log its argument to a variable:

const originalLogFunction = console.log;
let output;
beforeEach(function(done) {
  output = '';
  console.log = (msg) => {
    output += msg + '\n';
  };
});
afterEach(function() {
  console.log = originalLogFunction; // undo dummy log function
  if (this.currentTest.state === 'failed') {
    console.log(output);
  }
});

You might need to modify the dummy log function in case you are supplying more than one argument or objects. This is a simplified example.

Problem

My Problem I'm writing a test suite for a Node.js application using Mocha. The functions that I'm testing write their logs to `console.log` directly, without any third-party logging solution. I don't care about logs from successful tests, just from failed tests, and since my functions are pretty verbose the test output is unnecessarily long. What Have I Tried - SFTW. Found this (Suppress console log of successful mocha tests), but it refers to Winston logs. My Question How can I suppress `console.log` output from passing / successful Mocha tests?

Original source