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 want to 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();

I found that the answer above re: suppressing console.log across all test suites threw errors when any other console methods (e.g. warn, error) were called since it was replacing the entire global console object.

This somewhat similar approach worked for me with Jest 22+:

package.json

"jest": {
  "setupFiles": [...],
  "setupTestFrameworkScriptFile": "<rootDir>/jest/setup.js",
  ...
}

jest/setup.js

jest.spyOn(global.console, 'log').mockImplementation(() => jest.fn());

Using this method, only console.log is mocked and other console methods are unaffected.