React-testing-library: Entire error output to console during a .toThrow() assertion

Created on 14 Aug 2018  路  4Comments  路  Source: testing-library/react-testing-library

  • react-testing-library version: 5.0.0
  • react version: 16.4.2
  • node version: 8.11.3
  • npm (or yarn) version: yarn 1.9.4

Relevant code or config:

const Component = props => {
    if (props.throw) throw new Error('!!')
    return <div>馃榾</div>
}
it('Throws an error when `props.throw === true`', () => {
    const renderComponent = () => render(<Component throw />)
    expect(renderComponent).toThrow('!!')
})

What you did:

I'm making a jest assertion that a component will throw an error under certain circumstances.

What happened:

While the test itself passes, the entire error shows up in the Jest output. Under other circumstances, jest suppresses errors that are thrown within a .toThrow() assertion. (there's a test in the repo that shows this)

Reproduction:

https://github.com/good-idea/rtl-throws-error

Problem description:

Lots of unnecessary console output!

Suggested solution:

I haven't looked into how jest / RTL handles all of this and how it might be happening, but I'm happy to put together a PR. Just point me in the right direction!

Most helpful comment

For anyone else coming here with the same problem, putting this in my setup file has it work exactly as I'd expect:

console.error = err => { throw new Error(err); };
console.warn = warning => { throw new Error(warning); };

All 4 comments

This actually is not something that has anything to do with react-testing-library. It's how react and jsdom work. You can silence these logs using mock functions. That's what I do.

Oh, got it ~ I hadn't come across this until I started using react-testing-library so I thought it was a problem on that side.

Thanks for the quick response!

For anyone else coming here with the same problem, putting this in my setup file has it work exactly as I'd expect:

console.error = err => { throw new Error(err); };
console.warn = warning => { throw new Error(warning); };

This actually is not something that has anything to do with react-testing-library. It's how react and jsdom work. You can silence these logs using mock functions. That's what I do.

For everyone wondering: This is an easy way to do it: https://til.hashrocket.com/posts/hrhejhqg2n-turn-off-console-error-messages-in-a-test

Was this page helpful?
0 / 5 - 0 ratings