'Mocha: Hide console.log output from successful tests
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?
Solution 1:[1]
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.
Solution 2:[2]
This is utterly simple with Mocha Suppress Logs.
Just install it:
npm install --save-dev mocha-suppress-logs
and EITHER add it to your Mocha command:
mocha --require mocha-suppress-logs
OR put this in your Mocha config to make it the default:
"require": "mocha-suppress-logs"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Thomas Dondorf | 
| Solution 2 | Inigo | 
