Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove logging the origin line in Jest

Jest has this feature to log the line that outputs to console methods.

In some cases, this can become annoying:

  console.log _modules/log.js:37
  ℹ login.0 screenshot start

  console.time _modules/init.js:409
  login.0.screenshot: 0.33ms

  console.time _modules/init.js:394
  0 | login.0: 0.524ms

  console.log _modules/log.js:37
  ℹ login.1 screenshot start

Any idea how I can turn it off?

like image 883
Dejan Toteff Avatar asked Jul 27 '18 10:07

Dejan Toteff


People also ask

How do I hide console log in jest?

To disable console inside unit tests with Jest, we can use the --silent option or set the console methods to mocked functions. to run jest with the --silient to disable console output when running tests.

Does console log work in jest?

Jest by default prints all console. log (warnings, errors, etc) messages to the console. That's great - it helps you understand what's going on in your code when tests run.

What is JavaScript logging?

As with many other programming languages, JavaScript has support for logging messages at various levels. They are as follows, with their associated method and a description of their output in the console: Plaintext—console. log() outputs unstyled text. Info—console.info() typically outputs text with a blue background.


2 Answers

With Jest 24.3.0 or higher, you can do this in pure TypeScript by adding the following to a Jest setup file configured in setupFilesAfterEnv:

import { CustomConsole, LogType, LogMessage } from '@jest/console';

function simpleFormatter(type: LogType, message: LogMessage): string {
    const TITLE_INDENT = '    ';
    const CONSOLE_INDENT = TITLE_INDENT + '  ';

    return message
        .split(/\n/)
        .map(line => CONSOLE_INDENT + line)
        .join('\n');
}

global.console = new CustomConsole(process.stdout, process.stderr, simpleFormatter);
like image 161
Harald Wellmann Avatar answered Sep 19 '22 15:09

Harald Wellmann


Jest injects custom console implementation that is based on extendable Console class into test global scope. Normally it provides useful debugging information alongside printed message that answers the question where potentially unwanted output comes from.

In case this is undesirable for some reason, a simple way to retrieve default console implementation is to import it from Node built-in module.

Can be done for specific console calls:

let console = require('console');    
...
console.log(...)

For many of them that occur inside a range of tests:

const jestConsole = console;

beforeEach(() => {
  global.console = require('console');
});

afterEach(() => {
  global.console = jestConsole;
});

And so on.

like image 40
Estus Flask Avatar answered Sep 17 '22 15:09

Estus Flask