Dejan Toteff
Dejan Toteff

Reputation: 2207

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?

Upvotes: 18

Views: 5067

Answers (7)

vikonnikov
vikonnikov

Reputation: 1

Add to setupTests.js

import console from "console"
global.console = console

Upvotes: 0

manit
manit

Reputation: 694

// jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testMatch: ['**/__tests__/**/*.ts'],
  setupFilesAfterEnv: ["./jest.custom.config.js"]
};

// jest.custom.config.js

global.console = {
    ...console,
    log: jest.fn((message) => process.stdout.write(`${message}\n`)), // Override to show logs in real-time
  };

Upvotes: 1

theCrazySander
theCrazySander

Reputation: 184

None of the above options worked for me.

The (current) simplest solution is this:

1: Create a file with this code (e.g. config.js)

import console from "console"
global.console = console

2: Add this line to your jest.config.js

setupFilesAfterEnv: ["./config.js"]

Before:

Remove logging the origin line in Jest

After:

Remove logging the origin line in Jest

Enjoi!

Upvotes: 9

Hans
Hans

Reputation: 359

If you want to use Haral Wellmann's answer but avoid typescript, then you can merely do something like:

const JestConsole = require('./node_modules/@jest/console');
global.console = new JestConsole.CustomConsole(process.stdout, process.stderr, (type, message) => {
    const TITLE_INDENT = '    ';
    const CONSOLE_INDENT = TITLE_INDENT + '  ';
    return message.split(/\n/).map(line => CONSOLE_INDENT + line).join('\n');
  });

Upvotes: 3

Anders Carstensen
Anders Carstensen

Reputation: 4124

Update: For newer versions of Jest, see Harald Wellmann's answer.


Looking at the source code for Jest, it doesn't seem like there is a neat way to turn those messages off.

However, one possible solution could be to write your own Console. Here I have used Console.js from Jest as a starting ground, and then created SimpleConsole which does what you need (I have removed some terminal coloring features for simplicity, but you could just add them yourself).

Once added to your project, you can overwrite Jest's normal console with your own before running the tests:

const { SimpleConsole } = require('./SimpleConsole');
global.console = new SimpleConsole(process.stdout, process.stderr);

I have made a REPL that shows it in action.

The source code for SimpleConsole:

const path = require('path');
const assert = require('assert');
const {format} = require('util');
const {Console} = require('console');

function simpleFormatter() {
  const TITLE_INDENT = '    ';
  const CONSOLE_INDENT = TITLE_INDENT + '  ';

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

    return (
      message +
      '\n'
    );
  };
};

class SimpleConsole extends Console {
  constructor(stdout, stderr, formatBuffer) {
    super(stdout, stderr);
    this._formatBuffer = formatBuffer || simpleFormatter();
    this._counters = {};
    this._timers = {};
    this._groupDepth = 0;
  }

  _logToParentConsole(message) {
    super.log(message);
  }

  _log(type, message) {
    if (process.stdout.isTTY) {
      this._stdout.write('\x1b[999D\x1b[K');
    }
    this._logToParentConsole(
      this._formatBuffer(type, '  '.repeat(this._groupDepth) + message),
    );
  }

  assert(...args) {
    try {
      assert(...args);
    } catch (error) {
      this._log('assert', error.toString());
    }
  }

  count(label = 'default') {
    if (!this._counters[label]) {
      this._counters[label] = 0;
    }

    this._log('count', format(`${label}: ${++this._counters[label]}`));
  }

  countReset(label = 'default') {
    this._counters[label] = 0;
  }

  debug(...args) {
    this._log('debug', format(...args));
  }

  dir(...args) {
    this._log('dir', format(...args));
  }

  dirxml(...args) {
    this._log('dirxml', format(...args));
  }

  error(...args) {
    this._log('error', format(...args));
  }

  group(...args) {
    this._groupDepth++;

    if (args.length > 0) {
      this._log('group', chalk.bold(format(...args)));
    }
  }

  groupCollapsed(...args) {
    this._groupDepth++;

    if (args.length > 0) {
      this._log('groupCollapsed', chalk.bold(format(...args)));
    }
  }

  groupEnd() {
    if (this._groupDepth > 0) {
      this._groupDepth--;
    }
  }

  info(...args) {
    this._log('info', format(...args));
  }

  log(...args) {
    this._log('log', format(...args));
  }

  time(label = 'default') {
    if (this._timers[label]) {
      return;
    }

    this._timers[label] = new Date();
  }

  timeEnd(label = 'default') {
    const startTime = this._timers[label];

    if (startTime) {
      const endTime = new Date();
      const time = endTime - startTime;
      this._log('time', format(`${label}: ${time}ms`));
      delete this._timers[label];
    }
  }

  warn(...args) {
    this._log('warn', format(...args));
  }

  getBuffer() {
    return null;
  }
}

module.exports.SimpleConsole = SimpleConsole;

Upvotes: 6

Estus Flask
Estus Flask

Reputation: 222538

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.

Upvotes: 14

Harald Wellmann
Harald Wellmann

Reputation: 12865

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);

Upvotes: 23

Related Questions