Reactjs – Jest, Unexpected Token Import

babel-jestjestjsreactjs

I start a new react project and I wand to use Jest as testing platform. Despite docs, blogs and many others resources like stackoverflow, I have always an "unexpected token import" error related probably to a babel problem, but my conf seem to be ok. Any help is welcomed.

My Jest conf (in package.json). My package.json has dependencies like babel-jest, babel-preset-es2015, babel-preset-react, etc.

 "jest": {
    "testMatch": [
      "**/?(*.)spec.js?(x)"
    ],
    "moduleDirectories": [
      "src",
      "node_modules"
    ],
    "moduleNameMapper": {
      "^lib/(.*)$": "<rootDir>/src/lib/$1",
      "^components/(.*)": "<rootDir>/src/components/$1",
    },
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    }

My .babelrc conf :

{
  "presets": [
    ["es2015", { "modules": false }],
    "react"
  ],
  "plugins": [
    ["react-hot-loader/babel"],
    ["transform-object-rest-spread", { "useBuiltIns": true }],
    ["transform-runtime"]
  ],
  "env": {
      "test": {
        "presets": ["es2015", "react"]
      }
  } 
}

My spec file :

import React from 'react';
import Radio from 'components/ui/radio';
...

And components/ui/radio (import error is raised on the first line) :

import Container from './container.jsx';
...

My webpack has two alias named lib and components (define as moduleNameMapper in jest).

...
resolve: {
   mainFiles: ['index', 'main'],
   extensions: ['.js', '.jsx'],
   alias: {
     lib: helpers.getPath('src/lib/'),
     components: helpers.getPath('src/components/'),
   },
   modules: [
     helpers.getPath('src'),
     helpers.getPath('node_modules'),
   ],
}, 
...

Best Answer

I had a very similar issue and at the end I solved it just using --no-cache when running jest.

I also had in my package.json dependencies like babel-jest, babel-preset-es2015, babel-preset-react, etc.

jest --no-cache
Related Topic