How do I setup jest to use custom babel plugin in create-react-app project?

834 Views Asked by At

I have a CRA project and i use react-intl package, with its babel-plugin-formatjs (to auto generate message IDs for translation).

I created wrapper around the babel-plugin-formatjs that gets some additional info about project and

In order to use the custom babel plugin in CRA, i use customize-cra package with a config-overrides.js file in the root folder like so:

const { override, addBabelPlugin } = require('customize-cra');

function getMyCustomBabelPlugin() {
  // extract some info and return the plugin config:
  return ['babel-plugin-formatjs', { ... // some custom config }]
}

module.exports = {
  webpack: override(
    ... // some overrides,
    addBabelPlugin(getMyCustomBabelPlugin()),
  ),
}

So whenever i run the build command babel runs the babel-plugin-formatjs (and adds id to strings for translation).

But whenever I want to run the CRA test command, jest doesn't pick up the babel config. Some of my tests render components that use react-intl and i get errors: [@formatjs/intl] An id must be provided to format a message. because my custom plugin does not run.

I see that under the hood CRA runs createJestConfig() with the default config. How can i make jest to use the wanted babel plugins? Or alternatively, How do I pass jest additional plugins without ejecting or ignoring the default createJestConfig() of CRA?

I tried creating a babel.config.js file in the root folder with the custom babel plugin, but jest doesn't pick that up. Also saw this answer https://stackoverflow.com/a/62861130/8252705 But wondering if it might have changed as its an old answer.

1

There are 1 best solutions below

1
On

I think that may help you - https://github.com/arackaf/customize-cra/blob/master/api.md#usebabelrc

as addBabelPlugin does not affect config for testing, so useBabelRc picks babel config file and override default CRA's babel config