How to suppress application registration messages from node.js application while running unit tests?

When unit testing my node.js application (which is basically a REST backend) using mocha and supertest, I only need a test message on the screen, but stdout is also cluttered with application log messages.

I run unit test with

mocha -R spec . 

... and get this output (this should not be):

 [App] Listening on port 3000 ... [App] Starting app, hooray! Project API GET /projects [App] entering "projects" module ... √ should return an array of projects (317ms) 

I marked the application log message using [App]. What I really want will be this output from unit test:

  Project API GET /projects √ should return an array of projects (317ms) 

How can I suppress console.log / warn / error output with an application interleaved with Mocha reporter output?

DECISION:

Following the dankohn approach, I ended up solving my problem (using winston for logging):

(in the node "main" server file, server.js :)

 if (process.env.NODE_ENV !== 'test') { logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)(), new (winston.transports.File)({ filename: 'foo.log' }) ] }); } else { // while testing, log only to file, leaving stdout free for unit test status messages logger = new (winston.Logger)({ transports: [ new (winston.transports.File)({ filename: 'foo.log' }) ] }); } 

... and to set the env variable, each unit test file starts with:

 process.env.NODE_ENV = 'test'; 
+43
unit-testing mocha
Mar 28 '14 at 10:15
source share
2 answers

In your app.js application:

 if (process.env.NODE_ENV !== 'test') { app.use(express.logger()); } 

At the top of each of your mocha files:

 process.env.NODE_ENV = 'test'; 

Update:

We use this function in our import code:

 function logExceptOnTest(string) { if (process.env.NODE_ENV !== 'test') { console.log(string); } } 

Then replace all your console.log('it worked') with logExceptOnTest('it worked') . The main trick is to use environment variables as a global flag regarding the logging level you want.

+29
Mar 28 '14 at 10:46
source share

Already answered, but thought I'd add that you can make this user winston.add ()

 var logger = new (winston.Logger)({ transports: [ new (winston.transports.File)({filename: 'node.log'}) ] }); if (process.env.NODE_ENV === 'test') { logger.add(winston.transports.Console, {prettyPrint: true}); } 
+7
Oct 21 '15 at 22:08
source share



All Articles