How to hide JavaScript’s console.log output in Jest tests

I was working today in a codebase that had many intentional console.log output in all environments but production so they were showing up in Jest tests output. It would have been tedious to go and remove them one by one and so I devised this simple setup to suppress all console.log output at once while Jest is running.

Configuring Jest

This trick relies on Jest’s native ability to mock anything. What we’ll basically do is to mock the log method of the console object and leave the other methods intact.

We first need to tell Jest to execute a setup file before the tests are run. To do this, we’ll edit the jest.config.js file that’s usually at the root of your project with other configuration properties, and add the following line:

setupFilesAfterEnv: ['<rootDir>/src/jest.setup.js']

We can check in Jest’s documentation what the setupFilesAfterEnv does:

A list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed.

Now, when we run our tests, they’ll first execute the `jest.setup.js` that we will create now.

Mocking console.log

Create a file at src/setup.js or wherever you pointed your path in the previous step. You’ll then add this to it:

global.console = {
    log: jest.fn(),
    debug: console.debug,
    trace: console.trace,
    // map other methods that you want to use like console.table
}

This is overriding the log method, and allowing the others. Since I still wanted to have the ability to output something in the tests, I mapped debug and trace. You can map others that you might need like `console.table` that renders elements in a table, useful to log objects or arrays. To be honest, until I wrote this, I had never looked at the console object page in MDN and there are many interesting methods like the console.dir that displays an interactive list of the properties of the specified JavaScript object.

Closing words

Now your console.log output is suppressed while your Jest tests run. If you work in a team make sure you let the rest of the team know about this change by documenting it since someone might get stressed out trying to console.log something and not seeing it where it should be.

1 thought on “How to hide JavaScript’s console.log output in Jest tests”

Leave a Reply