javascript - 如何在 Jest 测试中调用 native console.log 方法?

标签 javascript jestjs

Jest 覆盖了原生的 console.log 方法来收集每个测试的日志输出。然而,这会使使用调试器变得非常困难,因为不会打印任何内容。

enter image description here

有没有办法在 Jest 测试中调用 native console.log 方法?

最佳答案

您可以通过传递自定义 TestEnvironment 和自定义 Reporter(使用 jest@24.7.1 测试)来实现此目的:

// debugTestEnv.js

const NodeEnvironment = require('jest-environment-node')
const console = require('console')

const vanillaConsole = new console.Console({ stdout: process.stdout, stderr: process.stderr })

class DebugTestEnv extends NodeEnvironment {
  async setup() {
    await super.setup()
    this.prevConsole = this.global.console
    this.global.console = vanillaConsole
  }

  async teardown() {
    this.global.console = this.prevConsole
    await super.teardown()
  }
}

module.exports = DebugTestEnv

// debugReporter.js

// In Jest, the DefaultEnvironment constructor changes `process.stdout` and `process.stderr`
// That's why we pass a custom reporter to Jest (we use Jest's BaseReporter for this purpose)
module.exports = require('@jest/reporters/build/base_reporter').default

然后运行一个特定的测试:

jest --runInBand --no-cache --watchAll=false -t="testNameToDebug" --env="./path/to/debugTestEnv.js" --reporters="./path/to/debugReporter.js"

这也适用于 create-react-app,只需将 jest 替换为 react-scripts test

关于javascript - 如何在 Jest 测试中调用 native console.log 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52904431/

相关文章:

javascript - Google map api 标记未定义错误

javascript - 开 Jest 单元测试: setTimeout not firing in async test

reactjs - 使用 enzyme/jest 关闭后,reactstrap 模态中的内容继续存在

javascript - 访问数组中的 JSON 对象

javascript - Angular ng-view 或 ng-include 不起作用

angular - 我可以通过 Angular CLI 运行 Jest 吗?

javascript - 在 Jest 中模拟按钮点击

javascript - 如何使用 Jest 模拟第三方包?

javascript - 从 Angular Controller 调用 webview 方法

javascript - Kendo UI Editor - 强制所有新链接到新窗口