首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Jest测试中调用原生console.log方法?

如何在Jest测试中调用原生console.log方法?
EN

Stack Overflow用户
提问于 2018-10-20 17:54:45
回答 1查看 263关注 0票数 2

Jest覆盖原生console.log方法来收集每个测试的日志记录输出。但是,这会使使用调试器变得相当困难,因为不会打印任何内容。

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

EN

回答 1

Stack Overflow用户

发布于 2019-06-06 18:02:49

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

代码语言:javascript
复制
// 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
代码语言:javascript
复制
// 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

然后运行特定的测试:

代码语言:javascript
复制
jest --runInBand --no-cache --watchAll=false -t="testNameToDebug" --env="./path/to/debugTestEnv.js" --reporters="./path/to/debugReporter.js"

这也适用于create-react-app,只需用react-scripts test替换jest即可。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52904431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档