1

I'm testing my app with jest but there is a small problem related with my logger: its keeps sending console logs while testing routes.

Im dealing with a basic winston configuration for my logger:

logger.config.js

const winston = require('winston');
const { env } = require('./variables.config.js');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

if (env === 'development') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

logger.stream = {
  write: (message) => {
    logger.info(message.trim());
  }
};

module.exports = logger;

index.js

const app = require('./config/express.config');
const logger = require('./config/logger.config');

const server = app.listen(port, logger.info(`Running on port ${port} (${env})`));

module.exports = server;

I'm using server on my tests as well as supertest:

some.test.js

const request = require('supertest');
const app = require('../../config/express.config');

...and, yeah... Every single request shows a log on my console which I don't want. How can I prevent my logger to display messages while testing my app?

Thanks in advance!

skyboyer
  • 22,209
  • 7
  • 57
  • 64
enbermudas
  • 1,603
  • 4
  • 20
  • 42

1 Answers1

0

In tests, you can use mocks to simulate behavior of winton, long story short you can create dummy winston module which only pretend logging.

You can define a custom mock for winston in a __mocks__ folder in your project root (defined in jest config!). So you can create __mocks__/winston.js with mocked function you use and Jest automatically loads this module for test purposes. Also you can specify custom path to your mock:

jest.mock('foo', () => jest.requireActual('../some/another/folder/foo.js'));

Check a Jest manual for more info, or if you new in a mocking check this or this

l2ysho
  • 2,542
  • 1
  • 20
  • 41