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.
How can I suppress console.log
output from passing / successful Mocha tests?
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.