Categories
JavaScript Answers

How to disable console inside unit tests with Jest?

Spread the love

Sometimes, we want to disable console inside unit tests with Jest.

In this article, we’ll look at how to disable console inside unit tests with Jest.

How to disable console inside unit tests with Jest?

To disable console inside unit tests with Jest, we can use the --silent option or set the console methods to mocked functions.

For instance, we run

jest --silent

to run jest with the --silient to disable console output when running tests.

Or we can create a tests/setup.js file with

global.console = {
  ...console,
  log: jest.fn(),
  debug: jest.fn(),
  info: jest.fn(),
  warn: jest.fn(),
  error: jest.fn(),
};

to set all the console methods to mocked functions.

And then we can use the config by writing

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

to add tests/setup.js to the setupFilesAfterEnv array in jest.config.js to load that when running tests.

Conclusion

To disable console inside unit tests with Jest, we can use the --silent option or set the console methods to mocked functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *