如何在运行unit testing时抑制来自node.js应用程序的应用程序日志消息?
当使用mocha和supertest对我的node.js应用程序(基本上是一个REST后端)进行unit testing时,我只需要在屏幕上显示特定于testing的消息,但stdout也与应用程序日志消息混杂在一起。
我开始unit testing:
mocha -R spec . …并得到这个输出(这是不应该的):
 [App] Listening on port 3000 ... [App] Starting app, hooray! Project API GET /projects [App] entering "projects" module ... √ should return an array of projects (317ms) 
我用[App]标记了应用程序日志消息。 我真正想要的是unit testing的输出结果:
  Project API GET /projects √ should return an array of projects (317ms) 
我怎样才能抑制散布摩卡的记者输出应用程序的console.log /警告/错误输出?
解:
按照丹科的方法,我结束了这个,解决了我的问题(使用winston进行logging):
(在节点的“主”服务器文件中,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' }) ] }); } 
…并设置envvariables,每个unit testing文件开始于:
 process.env.NODE_ENV = 'test'; 
	
在你的app.js中:
 if (process.env.NODE_ENV !== 'test') { app.use(express.logger()); } 
在每个摩卡文件的顶部:
 process.env.NODE_ENV = 'test'; 
更新:
我们在导入代码中使用这个函数:
 function logExceptOnTest(string) { if (process.env.NODE_ENV !== 'test') { console.log(string); } } 
 然后,用logExceptOnTest('it worked')replace所有的console.log('it worked') logExceptOnTest('it worked') 。 基本的技巧是使用环境variables作为你想要的日志级别的全局标志。 
已经回答,但认为我会补充说,你可以做这个用户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}); }