Node.js Silence Middleware Output When Testing

So I wanted to have the console output of my tests clean and not polluted by node app middleware output, such as that output by request modules when performing http requests. I remember briefly touching on this subject before when Silencing Log Output when testing.

This is what the output looks like when I run my tests.

middleware output request testing

So how do you silence node.js middleware output when running tests? I guess the easiest way would be to set the request package to be slient. I couldn’t see such an option in the Request Module. Is this possible?

Another Solution

Another solution I saw was to use a logging package called Winston Module.

“Winston is a multi-transport async logging library for Node.js.”

This solution worked quite well and it now only shows the output from the mocha tests.

solution output nodejs

Include Winston package and add this code to the top of your test file.

process.env.NODE_ENV = 'test' //you can set this based on your environment or at the top of the test files.

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

     //suppress console.log to fileoutput only when testing
     logger = new (winston.Logger)({
          transports: [
              new (winston.transports.File)({ filename: 'test.log' })
          ]
     });

}

That’s it, no more crap in your test output. Suit you sir.