Mocha Test Silence Log Output

When testing my server I have log output which I don’t want to appear when I run my tests using Mocha. I want to Silence Log Output!!! Ofcourse a solution is suggested by TJ! Let’s take a look…

OK, so include this in your server.js file.

// api middleware
if (process.env.NODE_ENV !== 'test') {
  api.use( logger( 'dev' ) );     /* 'default', 'short', 'tiny', 'dev' */
}

Then, include this at the top of your test files.

//suppress stdout when running unit tests
process.env.NODE_ENV = 'test';

Then, include this in your custom console.log util function.

//custom console.log function
Utils.prototype.log = function( msg ) {

     //suppress console.log messages when in test mode
     if (process.env.NODE_ENV !== 'test') {
          console.log( msg );
     }

}

That’s pretty much it, a useful way to silence that output (when you need to). Further reading on this topic see Node.js Silence Middleware Output When Testing.