Jest has this feature to log the line that outputs to console
methods.
In some cases, this can become annoying:
console.log _modules/log.js:37
ℹ login.0 screenshot start
console.time _modules/init.js:409
login.0.screenshot: 0.33ms
console.time _modules/init.js:394
0 | login.0: 0.524ms
console.log _modules/log.js:37
ℹ login.1 screenshot start
Any idea how I can turn it off?
To disable console inside unit tests with Jest, we can use the --silent option or set the console methods to mocked functions. to run jest with the --silient to disable console output when running tests.
Jest by default prints all console. log (warnings, errors, etc) messages to the console. That's great - it helps you understand what's going on in your code when tests run.
As with many other programming languages, JavaScript has support for logging messages at various levels. They are as follows, with their associated method and a description of their output in the console: Plaintext—console. log() outputs unstyled text. Info—console.info() typically outputs text with a blue background.
With Jest 24.3.0 or higher, you can do this in pure TypeScript by adding the following to a Jest setup file configured in setupFilesAfterEnv
:
import { CustomConsole, LogType, LogMessage } from '@jest/console';
function simpleFormatter(type: LogType, message: LogMessage): string {
const TITLE_INDENT = ' ';
const CONSOLE_INDENT = TITLE_INDENT + ' ';
return message
.split(/\n/)
.map(line => CONSOLE_INDENT + line)
.join('\n');
}
global.console = new CustomConsole(process.stdout, process.stderr, simpleFormatter);
Jest injects custom console implementation that is based on extendable Console
class into test global scope. Normally it provides useful debugging information alongside printed message that answers the question where potentially unwanted output comes from.
In case this is undesirable for some reason, a simple way to retrieve default console
implementation is to import it from Node built-in module.
Can be done for specific console calls:
let console = require('console');
...
console.log(...)
For many of them that occur inside a range of tests:
const jestConsole = console;
beforeEach(() => {
global.console = require('console');
});
afterEach(() => {
global.console = jestConsole;
});
And so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With