Search code examples
reactjstypescriptjestjscreate-react-app

How can I enable decorators support when running tests with CRA 2.1?


I am trying to get the tests of a React application that uses decorators and Typescript to work with Create React App v2.1.0

I am aware that decorators are not officially supported.

I can run the application fine thanks to React App Rewired and @babel/plugin-proposal-decorators.

Where I am stuck is to enable decorator support when running the tests.

My npm test script is : "test": "react-app-rewired test --env=jsdom --runInBand"

Tests fails with:

The 'decorators' plugin requires a 'decoratorsBeforeExport' option, whose value must be a boolean. If you are migrating from Babylon/Babel 6 or want to use the old decorators proposal, you should use the 'decorators-legacy' plugin instead of 'decorators

I have tried to add a .babelrc file with the following :

{
  "plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }]]
}

but get hit by:

Cannot use the decorators and decorators-legacy plugin together


Solution

  • 👋 I'm a Create React App maintainer.

    Decorators are supported if you're using TypeScript and work with tests, no extra configuration required (CRA ^2.1.1, there was a bug in 2.1.0).

    Decorators are only unsupported in JavaScript.


    First, remove react-app-rewired and switch your scripts back to react-scripts. Next, remove your .babelrc file.

    Finally, convert any files using decorators to be TypeScript files (.tsx). Everything should just work now!

    Also, your test script should only read "test": "react-scripts test" or "test": "react-scripts test --runInBand". Passing --env=jsdom is unnecessary as specified in the 2.0 upgrade guide.