Fix "Jest encountered an unexpected token" with "create-react-app"

tmhao2005

tmhao2005

Posted on September 6, 2020

Fix "Jest encountered an unexpected token" with "create-react-app"

Here is one of the most popular question which is related to testing with jest for repo setup with create-react-app as I've seen in stackoverflow community. So I decided to come with a post on this with a hope to help more people via channel.

The problem is most likely as we install a 3rd party package which is untranspiled. By default Jest will skip to transform any packages in the node_modules.

Here are a few ways I have seen, assume the package is being used @fullcalendar:

  • Use a customized package react app customize-cra:
const { override, babelInclude } = require('customize-cra');
const path = require('path');

module.exports = override(
  babelInclude([
    path.resolve('src'), 
    path.resolve('node_modules/@fullcalendar')
  ]),
)
Enter fullscreen mode Exit fullscreen mode
  • Use the customized parameter passing to jest via react script
react-scripts test --transformIgnorePatterns \"node_modules/(?!@fullcalendar)/\"",
Enter fullscreen mode Exit fullscreen mode

Of course most of above ways are to try to transform that package again but exclude the others in node_modules by setting transformIgnorePatterns. Unfortunately, the above 2 ways don't work as expected.

What is the best approach to fix?

The easiest way to fix this one is of course also using the same option transformIgnorePatterns but we just simply put in the package.json file under jest area since create-react-app still uses these options to override their default options:

jest": {
  "transformIgnorePatterns": [
    "/node_modules/(?!@fullcalendar)"
  ]
},
Enter fullscreen mode Exit fullscreen mode

Hopefully, it would help!

💖 💪 🙅 🚩
tmhao2005
tmhao2005

Posted on September 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related