删除 Jest 中记录原始行

问题描述 投票:0回答:6

Jest 具有此功能来记录输出到

console
方法的行。

在某些情况下,这可能会变得烦人:

  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

知道如何将其关闭吗?

javascript node.js logging jestjs
6个回答
22
投票

使用 Jest 24.3.0 或更高版本,您可以通过将以下内容添加到

setupFilesAfterEnv
中配置的 Jest 安装文件中,以纯 TypeScript 执行此操作:

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

14
投票

Jest 将基于可扩展

Console
的自定义控制台实现注入到测试全局范围中。通常,它会提供有用的调试信息以及打印消息,回答潜在不需要的输出来自何处的问题。

如果由于某种原因不希望出现这种情况,检索默认

console
实现的一个简单方法是从 Node 内置模块导入它。

可以针对特定控制台调用完成:

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

对于在一系列测试中发生的许多问题:

const jestConsole = console;

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

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

等等。


7
投票

以上选项都不适合我。

(当前)最简单的解决方案是这样的:

1:使用此代码创建一个文件(例如 config.js)

import console from "console"
global.console = console

2:将此行添加到您的 jest.config.js 中

setupFilesAfterEnv: ["./config.js"]

之前:

Remove logging the origin line in Jest

之后:

Remove logging the origin line in Jest

享受!


6
投票

更新: 对于较新版本的 Jest,请参阅 Harald Wellmann 的回答。


查看 Jest 的源代码,似乎没有一个巧妙的方法来关闭这些消息。

但是,一种可能的解决方案是编写自己的控制台。在这里,我使用 Jest 中的 Console.js 作为起点,然后创建

SimpleConsole
来满足您的需求(为了简单起见,我删除了一些终端着色功能,但您可以自己添加它们)。

添加到您的项目后,您可以在运行测试之前用您自己的控制台覆盖 Jest 的普通控制台:

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

我制作了一个 REPL 来展示它的实际效果。

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;

3
投票

如果您想使用 Haral Wellmann 的答案但避免使用打字稿,那么您只需执行以下操作:

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

0
投票

//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
  };
© www.soinside.com 2019 - 2024. All rights reserved.