删除在Jest中记录原始线

Dej*_*eff 2 javascript logging node.js jestjs

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
Run Code Online (Sandbox Code Playgroud)

知道如何关闭它吗?

Har*_*ann 13

使用 Jest 24.3.0 或更高版本,您可以在纯 TypeScript 中执行此操作,方法是将以下内容添加到在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);
Run Code Online (Sandbox Code Playgroud)

  • 在 JavaScript 中可以做到这一点吗?我有一个简单的 ES6 项目,不使用 Babel 或 TypeScript。 (2认同)

Est*_*ask 12

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

如果由于某种原因不需要这样做,检索默认console实现的一个简单方法是从 Node 内置模块导入它。

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

let console = require('console');    
...
console.log(...)
Run Code Online (Sandbox Code Playgroud)

对于其中许多发生在一系列测试中的情况:

const jestConsole = console;

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

afterEach(() => {
  global.console = jestConsole;
});
Run Code Online (Sandbox Code Playgroud)

等等。

  • 感谢您的反对票。输出确实会交织在一起,但我并没有说相反的情况。这取决于开发人员是否需要,但我认为如果目的是提供普通控制台输出,这是有意义的,如果日志不实时出现,则很难跟踪日志。我不完全理解OP的原始行的问题,但根据我的经验,延迟日志对于长时间的测试来说可能会很烦人。 (2认同)

And*_*sen 5

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

但是,一种可能的解决方案是编写您自己的控制台。在这里,我以Jest的Console.js为起点,然后创建SimpleConsole了满足您需要的功能(为简单起见,我删除了一些终端着色功能,但您可以自己添加它们)。

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

const { SimpleConsole } = require('./SimpleConsole');
global.console = new SimpleConsole(process.stdout, process.stderr);
Run Code Online (Sandbox Code Playgroud)

我制作了一个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;
Run Code Online (Sandbox Code Playgroud)


小智 4

上述选项都不适合我。

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

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

import console from "console"
global.console = console
Run Code Online (Sandbox Code Playgroud)

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

setupFilesAfterEnv: ["./config.js"]
Run Code Online (Sandbox Code Playgroud)

前:

删除 Jest 中的原始行记录

后:

删除 Jest 中的原始行记录

享受!