React-testing-library: Automatic cleanup fails badly when ReactDOM is mocked in a test file

Created on 10 Nov 2020  ·  6Comments  ·  Source: testing-library/react-testing-library

  • @testing-library/react version: 11.1.0
  • Testing Framework and version: jest 26.5.3
  • DOM Environment: jsdom 16.4.0
  • node 12.18
  • react 16.14

Relevant code or config:

jest.mock('react-dom');

What you did:

I was updating our configuration to follow most of the recommendations from https://kentcdodds.com/blog/common-mistakes-with-react-testing-library

When I removed our manual configuration of afterEach(cleanup) this started to break.

What happened:

This is the error I get:

  ● EmptyThreadIndicator › rendering › matches the snapshot when rendering all three types of indicators

    TypeError: Cannot read property 'current' of undefined

      64 | 
      65 |       const flushRafCalls = mockRaf(); // WithSize uses requestAnimationFrame
    > 66 |       const { container } = render(
         |                             ^
      67 |         // The props have to be passed in manually to avoid adding the SizeProps.
      68 |         <EmptyThreadIndicator
      69 |           rangeStart={props.rangeStart}

      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:909:55)
      at render (node_modules/@testing-library/react/dist/pure.js:94:26)
      at Object.<anonymous> (src/test/components/EmptyThreadIndicator.test.js:66:29)

Reproduction:

Problem description:

Suggested solution:

I don't have a suggested solution but a workaround: importing @testing-library/react from my setup.js file works fine.

Most helpful comment

OK then I won't update the issue more :-)

To be honest I don't know why we're mocking this here, I didn't write this code...

__update__: Actually simply removing the mock, the test still passes and now I don't have any issue with react-testing-library anymore. I don't know why this was there.

All 6 comments

(sorry, still updating the issue)

Hi @julienw, mocking react-dom is not recommended and will not work today and will never be supported...

If you want to use testing library's recommended testing techniques, you should let it use React DOM without mocking. If for some reason you can't or don't want to do this, you may want to use Enzyme's shallow renderer which doesn't require a DOM at all.

OK then I won't update the issue more :-)

To be honest I don't know why we're mocking this here, I didn't write this code...

__update__: Actually simply removing the mock, the test still passes and now I don't have any issue with react-testing-library anymore. I don't know why this was there.

Closing the issue then. Thanks for pointing me to the right direction!

Glad we got that squared away :)

Was this page helpful?
0 / 5 - 0 ratings