# Suppress console output from React in Jest testing output but not in browser output

I have a React app that I am testing with the built-in jest testing tools. In the process of debugging, I sometimes send data to the console (e.g. console.log, console.error, etc.) from my code-under-test. This shows up both in the browser console as well as in the testing output in the terminal which is what I sometimes want.

However, sometimes I want to send such debugging messages to either:

1. the testing terminal or
2. the browser,

but not both.

I know how to do #1: just include the console.log in the jest test code rather than in the code-under-test. However, if I want to do #2, I'm not quite sure what to do.

I tried the following in the code-under-test:

if (!jest) {
console.log('some browser-only output');
}


That does suppress the output in the test, which otherwise behaves normally, i.e. no error is thrown during testing. However, it does not output anything in the browser but instead throws an error: "Uncaught ReferenceError: jest is not defined", i.e. there is no let jest = ... or const jest = ... anywhere in the code.

I did come up with a solution:

try { jest; }
catch(e) {
console.log('some browser-only output');
}


This gives me the desired results. However, the solution feels very hack-y: It requires throwing an error in order to work, which just "smells" wrong, even for a debugging tool.

So, is there a better way for me to check whether jest exists without throwing an error? Or another way to see if testing is underway, again without throwing an error?

Use a way of checking for the jest global that won't throw an error:

if (typeof jest == 'undefined') {
console.log('some browser-only output');
}


You can also take advantage of the NODE_ENV environment variable:

if (process.env.NODE_ENV == 'development') {
console.log('browser');
} else if (process.env.NODE_ENV == 'test') {
console.log('jest');
}

• That difference that you point out between !myVar and typeof myVar === 'undefined' is not only applicable to this specific problem but also more generally as well, and a distinction I hadn't been previously been aware of. I'll probably use that elsewhere too. Thanks. – Andrew Willems May 8 '18 at 18:36

Hope this helps someone else: jest --silent

Then in your set up file, you can disable logging. For example, to disable console.log, you can do console.log = function() {}