'How to turn off logs from winston for jest

Currently I am testing a NodeJS app using jest. Particularly the system looks like this:

When I run tests, I like the log to be ordered. Especially at the first test and then dig into the logs. I know, that jest has the option --silent. Funnily this option does not apply to winston. The source code of winston looks like it is trying to directly write to stdout/err.

Does somebody know, how I can get winston to be silent while tests are running with the --silent option



Solution 1:[1]

you can utilize setupFilesAfterEnv jest option, by pointing it to a file that will mock console. for instance

add this to jest.config.js:

{
  ...
  setupFilesAfterEnv: ["./jest.setup.js"],
  ...
}

then create a file jest.setup.js

global.beforeAll(() => {
  console.error = jest.fn().mockImplementation(() => {});
  console.info = jest.fn().mockImplementation(() => {});
  console.log = jest.fn().mockImplementation(() => {});
});

The source code of winston looks like it is trying to directly write to stdout/err.

note that, since you configured winston to print to stdout\stderr, so the following advise above should do the trick. of course, you might wish to add an additional check for the --silent flag

otherwise, you can have a condition to silence winston by utilizing the silent property of winston transport

silent: If true, all logs are suppressed

Solution 2:[2]

To turn off winston logs for your Jest tests a best practice is to use the silent property of transporters together with NODE_ENV, like so:

var transporters = [new winston.transports.Console()];
if (process.env.NODE_ENV === 'test') {
  transporters[0].silent = true;
}

This approach works with all types of transports and gives you full control over which transporters are muted in the tests and which are not.

Note: Jest will set NODE_ENV to 'test' automatically. This behaviour is also useful for other test scenarios like loading test-configurations and so on.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr.
Solution 2 Sebastian