Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest with create-react-app - unexpected token errors

I am working on an application that was recently converted from an old Webpack build to use create-react-app. Most of the transition has went smoothly, but I'm running into some major issues with the previous unit tests. When I run npm test which has the standard package.json test script of "test": "react-scripts test --env=jsdom", it says all my snapshot tests have failed. This is fine and expected since there have been a lot of changes, and the tests need to be updated.

However, when I just run jest or jest --updateSnapshot, all of my tests immediately fail with SyntaxError: Unexpected token errors, most of which are related to import. This leads me to believe that Jest isn't using Babel to transform the ES6 syntax correctly.

Previously, we used a .babelrc file with these settings:

{
"presets": ["env", "react", "stage-0", "flow"],
"plugins": ["transform-runtime", "add-module-exports", "transform-decorators-legacy"]
}

But since Babel is already included in create-react-app I removed this file as well as any references to Babel. My package.json also does not have any special scripts set up for Jest itself.

I have tried adding some of the previously used Babel packages back in, but after further reading it seems those won't work anyway unless I eject from create-react-app and that is not an option at this time.

What would cause npm test to run correctly but jest to fail miserably?

like image 422
wildlifehexagon Avatar asked Feb 23 '18 22:02

wildlifehexagon


1 Answers

It turns out it was a Babel issue. Even though create-react-app comes pre-configured, we still had to add in custom configuration since our app wasn't initially built with cra. I installed some new dev dependencies:

"babel-cli": "^6.26.0",
"babel-jest": "^22.4.1",
"babel-preset-react-app": "^3.1.1",

And also updated the .babelrc:

{
  "presets": ["babel-preset-react-app"]
}

And now both jest and npm test both work as they should.

like image 78
wildlifehexagon Avatar answered Nov 02 '22 04:11

wildlifehexagon