create-react-app: TypeError: Class constructor App cannot be invoked without 'new'

If you are reporting a bug, please fill in below. Otherwise feel free to remove this template entirely.

Can you reproduce the problem with latest npm?

Yes Yes

Description

Trying to use React CSS Modules inside create-react-app, only during Jest tests, leads to:

TypeError: Class constructor App cannot be invoked without 'new'

Expected behavior

The code should work fine, like it happens when I use yarn start

Actual behavior

I get the error reported above.

Environment

Run these commands in the project folder and fill in their results:

  1. npm ls react-scripts (if you haven’t ejected): 0.9.4
  2. node -v: 7.5.0
  3. npm -v: 4.1.2

Then, specify:

  1. Operating system: macOS Sierra
  2. Browser and version: no browser

Reproducible Demo

This is a super simple repository created with create-react-app: https://github.com/FezVrasta/create-react-app-css-modules-bug

Just run yarn test to see the error. The only edited file is: https://github.com/FezVrasta/create-react-app-css-modules-bug/blob/master/src/App.js

Where I added react-css-modules

Note that this error happens only when I use create-react-app as base, in other repositories setup from scratch it works fine, but I can’t understand why.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 3
  • Comments: 15 (13 by maintainers)

Most upvoted comments

The problem here is likely that react-css-modules uses extends via Babel, but AFAIK you can’t extend a native class with a Babel-defined class due to the code Babel generates. Since we use native Node classes in Jest configuration, and your component is a native class, extending from it via Babel breaks.

While we could fix it by always applying the class transform, we gotta move to real ES classes at some point, so it’s still a time bomb. I would just suggest avoiding libraries that try to inherit from your classes, or bringing it up with those libraries to not use the Babel class transform.

I hope this helps!

Also, now that I think of it, I don’t really see why you’d want to apply react-css-modules in tests. So you might as well mock it to return component untouched:

jest.mock('react-css-modules', () => Component => Component);

This would probably circumvent the problem.