Disable winston logging when running unit tests?

2020-05-30 08:32发布

Can Winston logging be selectively disabled when executing unit tests of a node module?

Ideally, I'd like to have logging for informational and debug purposes when the application is running, but be suppressed as to not clutter the presentation unit test results when I run my tests.

My use of winston is internal to my module, something like this:

// MyModule.js
var logger = require('winston');
module.exports = function() {
  // does some stuff
  // and logs some stuff like so:
  logger.log('an informational message');
}

// MyModuleTest.js
describe('MyModule', fucntion() {
  it('should do some stuff', function() {
     var myModuleUnderTest = require('MyModule');
     // some tests
  }
}   

7条回答
何必那么认真
2楼-- · 2020-05-30 09:30

Sorry, I know this is a bit of an old question.

What I do is a bit ugly, but allows me to keep using Jest's --silent option normally. I just set Winston's silent to process.argv.indexOf("--silent") >= 0. For example:

const logger = new winston.Logger({
  …,
  transports: [
    new winston.transports.Console({
      …,
      silent: process.argv.indexOf("--silent") >= 0,
    }),
  ],
});
查看更多
登录 后发表回答