17

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

My Question

How can I suppress console.log output from passing / successful Mocha tests?

4 Answers 4

18

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"
Sign up to request clarification or add additional context in comments.

Comments

13

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.

1 Comment

This code does not compile with typescript in strict mode because currentTest property is missing.
0

Using sinon

Another answer here (currently accepted as of this posting) can be refactored to use the sinon stubbing library, like so:

const sinon = require('sinon');

let consoleOutput;  

beforeEach(function () {
  consoleOutput = '';
  sinon.stub(console, 'log').callsFake((msg) => {
    consoleOutput += msg + '\n';
  });
});

afterEach(function () {
  sinon.restore();
  if (this.currentTest.state === 'failed') {
    console.log(consoleOutput);
  }
});

Comments

0

IMHO, the way to do this is to log only when assert fails, like:

Before

console.log(foo);
assert.equal(1, 2);

After

assert.equal(1, 2, foo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.