Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 602
Adam Matan Avatar asked Nov 01 '18 11:11

Adam Matan


People also ask

How to suppress console output in Mocha?

My suggestion is to overwrite console.log with an empty function to suppress the output, allowing mocha to override it, without any changes to the reporters - maybe in the manner above using the well-known hooks.

Does stubbing console log suppress Mocha test reporting?

The problem with stubbing console.log is that it suppresses mocha's test reporting. Has anyone found a workaround for that? Sorry, something went wrong. then use it as usual.

Does console log work during tests?

Huge apologies! — console.log does work during tests! I must have been expecting it to suppress the output, and I didn't properly check my own code. Thanks for responding.

Is it possible to suppress console log output?

Like stated out in this issue #2084, it is very vital to suppress console.log output, when testing e.g. command line tools. All reporters seem to write to console.log while tests are running, so neither before nor beforeEach hooks will work to suppress the messy, mixed output. I tried it like this:


2 Answers

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.

like image 100
Thomas Dondorf Avatar answered Oct 07 '22 10:10

Thomas Dondorf


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"
like image 11
MatiasG Avatar answered Oct 07 '22 10:10

MatiasG