Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest, Unexpected Token Import

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'),
   ],
}, 
...
like image 406
Jerome Avatar asked Apr 17 '17 20:04

Jerome


People also ask

Where do you put transformIgnorePatterns?

I used transformIgnorePatterns right below the preset of jest in the package. json file. transformIgnorePatterns option can be used to specify which files shall be transformed by Babel.

What is a test suite in jest?

A test suite is a collection of test cases that are grouped for test execution purposes.” In other words you can think of it as a one-to-many relationship, where a test suite has many test cases.


1 Answers

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
like image 104
pearpages Avatar answered Sep 27 '22 22:09

pearpages