How to test console output (console.log, console.warn) with RTL (React-Testing-Library) and Jest

Ilya Zykin
2 min readApr 26, 2019

--

Let’s suppose you want to create a React component to render an Error Message. You don’t want to give any technical information to an end-point user, but want to have a way to check what error is happened.

Usually to catch all Javascript errors in an application developers use something like rollbar.com, catchjs.com, sentry.io and many other popular services.

But when you’re staring a development process for a new application you can do not have an access to this kind of tools and in this case the following code can be very helpful.

If you’re this kind of people who want to test everything you could ask yourself: “How to test this code?” and especially “How to test console output?”

Actually it’s really easy. The idea is to mock the console methods. Let’s do it.

We’re going to mock a console method. Do not forget that we have to restore this method after we have run our specs. Otherwise it can a cause of flaky tests.

Let’s save the original implementation of console.warn in a variable and be ensured that we restore it after each test case.

const originalWarn = console.warnafterEach(() => (console.warn = originalWarn))

For the first case we provides the following code

let consoleOutput = []
const mockedWarn = output => mockedWarn.push(output)
beforeEach(() => (console.warn = mockedWarn))

mockedWarn method will add all incoming data to consoleOutput array.

Before each test case we will replace the original implementation of console.warn with our one.

After the Error component is rendered we can check out output array

const { container } = render(<SystemError error={error} />)expect(consoleOutput).toEqual([
'errorName',
'errorMessage'
])

For the second case we will mock console.warn with a blank method just to avoid unnecessary output in terminal window during a test running.

const mockedWarn = () => {}
beforeEach(() => (console.warn = mockedWarn))

I’m reminding you that after all manipulations with console methods we have to restore our changes. We do it with the following line:

afterEach(() => (console.warn = originalWarn))

So. That is it.

  1. Now you’re able to test console output in your tests.
  2. You’re able to avoid unnecessary output in a terminal window when you run your tests.

Enjoy with development!

--

--

Ilya Zykin
Ilya Zykin

Written by Ilya Zykin

IT coach. React and Rails enthusiast. Passionate programmer, caring husband and pancake baker on Sundays. School teacher of computer studies in the past.