Jest: Better way to disable console inside unit tests Jest: Better way to disable console inside unit tests javascript javascript

Jest: Better way to disable console inside unit tests


For particular spec file, Andreas's is good enough. Below setup will suppress console.log statements for all test suites,

jest --silent

(or)

To customize warn, info and debug you can use below setup

__tests__/setup.js or jest-preload.js configured in setupFilesAfterEnv

global.console = {  log: jest.fn(), // console.log are ignored in tests  // Keep native behaviour for other methods, use those to print out things in your own tests, not `console.log`  error: console.error,  warn: console.warn,  info: console.info,  debug: console.debug,};

jest.config.js

module.exports = {    verbose: true,    setupTestFrameworkScriptFile: "<rootDir>/__tests__/setup.js",};

Jest v24.x Note: setupTestFrameworkScriptFile is deprecated in favor of setupFilesAfterEnv.

module.exports = {    verbose: true,    setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],};


If you wanna do it just for a specific test:

beforeEach(() => {  jest.spyOn(console, 'warn').mockImplementation(() => {});});


As every test file runs in its own thread there is no need to restore it if you want to disable it for all test in one file. For the same reason you can also just write

console.log = jest.fn()expect(console.log).toHaveBeenCalled();