React-testing-library: Can't get it to work with the new JSX transform in React 17 & create-react-app v4

Created on 28 Oct 2020  路  3Comments  路  Source: testing-library/react-testing-library

With the new JSX transform introduced in React (see: https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md) it is no longer necessary to import React at the top of each component - as it should be in scope "by default" when Webpack is correctly configured.

However if I attempt to do the same with test files I get the usual "_React is not defined_" error.
React has to be imported both in the target component & the test file for it to actually work.

Am I missing some configuration for this library or is this just not supported yet?

question

Most helpful comment

This is an issue with your Babel configuration, not React Testing Library. The .babelrc (which is only used by Jest) is missing "runtime": "automatic" so the new JSX transform is disabled. You can simplify your Babel configs and fix this by merging both your Babel configs into .babelrc with this option and removing the options from babel-loader, which I've done in mezei/react-testing-lib-new-transform#1.

All 3 comments

It doesn't look like this bug report has enough info for one of us to reproduce it.

Please provide a link to a repository on GitHub.

Here are some tips for providing a minimal example: https://stackoverflow.com/help/mcve

Here is a test repo with a simplified config:
https://github.com/mezei/react-testing-lib-new-transform

I'm not sure yet whether this is a bug or I'm just missing some configuration, babel transform setting, etc for either package, as there is no documentation for this case in react-testing-library (because this stuff is still very new).

The issue is that even though I can exclude calling import React from 'react'for most of my components (due to the new JSX transform), I still need to call this import for components which have unit tests. else I get the above error.

This is an issue with your Babel configuration, not React Testing Library. The .babelrc (which is only used by Jest) is missing "runtime": "automatic" so the new JSX transform is disabled. You can simplify your Babel configs and fix this by merging both your Babel configs into .babelrc with this option and removing the options from babel-loader, which I've done in mezei/react-testing-lib-new-transform#1.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

NiGhTTraX picture NiGhTTraX  路  3Comments

joshvillahermosa picture joshvillahermosa  路  3Comments

addamove picture addamove  路  3Comments

nagacoder picture nagacoder  路  3Comments

jaredmeakin picture jaredmeakin  路  3Comments