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

有没有办法在Jest测试中调用原生console.log方法?
发布于 2019-06-06 18:02:49
您可以通过传递自定义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,只需用react-scripts test替换jest即可。
https://stackoverflow.com/questions/52904431
复制相似问题