Reputation: 16561
Jest overrides the native console.log method to collect the logging output for each test. However that can make working with the debugger quite difficult, since nothing will be printed.
Is there a way to call the native console.log method inside a Jest test?
Upvotes: 3
Views: 541
Reputation: 551
You can achieve this by passing a custom TestEnvironment and and custom Reporter (tested with [email protected]):
// 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
then to run a particular test:
jest --runInBand --no-cache --watchAll=false -t="testNameToDebug" --env="./path/to/debugTestEnv.js" --reporters="./path/to/debugReporter.js"
This works as well with create-react-app, just replace jest
with react-scripts test
.
Upvotes: 1