Search code examples
jestjscreate-react-app

'Unexpected token import' while testing in create-react-app


when I run npm test in my project folder, I get an error message saying unexpected token import. As I am using create-react-app, I assume I don't have to configure anything because everything is supposed to work out-of-the-box.

I dont understand if I am making a mistake somewhere or its a create-react-app issue.


Solution

  • For anyone finding this question from Google:

    The error unexpected token import is often a sign that something is wrong with parsing your ES6 code, since import isn't a feature in earlier version. Often, browsers such as Chrome will run ES6, but you'll encounter the error when you go to run tests. Hence, running yarn test with create-react-app will expose this error.

    The immediate solution, is to look at how babel is compiling your ES6 code. In the example above, create-react-app has come with webpack and babel included. However, they assume that your node_modules are already compiled, and this are skipped over in the compiling process. So, even though you have babel in your project, it's not compiling all your ES6 for some reason.

    If you're using a different project that doesn't come with webpack/babel pre-setup, or wrote a custom setup for babel, that's where you should investigate first.