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?
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.
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.
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.
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:
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With