我如何在Jest测试中调用本地console.log方法?

时间:2018-10-20 09:54:45

标签: javascript jestjs

Jest覆盖本机console.log方法以收集每个测试的日志记录输出。但这会使调试器非常困难,因为将无法打印任何内容。

enter image description here

是否可以在Jest测试中调用本地console.log方法?

1 个答案:

答案 0 :(得分:0)

您可以通过传递自定义的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