Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest not parsing es6: SyntaxError: Unexpected token import

I am trying to setup Jest with my webpack project. When I run my tests, Jest complains it cannot read es6 code. Babel seems to not transform my test files.

I have tried various solutions I have found on the internet but I'm still stumped. Maybe somebody with more Babel/Webpack knowledge can look at my config and help me out.

relevant package.json script:

{
    "test": "jest --no-cache --config config/jest.config.js"
}

relevant package.json deps:

"@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.3.0",
"@babel/preset-env": "^7.3.1",
"@babel/preset-flow": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^24.0.0",
"babel-loader": "^8.0.5",
"babel-plugin-styled-components": "^1.10.0",
"jest": "^24.0.0",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1",
"webpack-dev-server": "^3.1.14"

config/webpack.config.js:

entry: './src/index.js',
mode: isProduction ? 'production' : 'development',
devtool: isProduction ? 'none' : 'inline-source-map',
bail: true,
devServer: {
  contentBase: 'build',
  compress: true,
  port: 3000,
},
output: {
  path: path.resolve(__dirname, 'build'),
  filename: '[name].[chunkhash].js',
},
module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          cacheDirectory: true,
          presets: [
            '@babel/preset-env',
            '@babel/preset-react',
            '@babel/preset-flow',
          ],
          plugins: [
            'babel-plugin-styled-components',
            '@babel/plugin-proposal-class-properties',
          ],
        },
      },
    },
  ],
},
plugins: [
  new HtmlWebpackPlugin({
    template: 'src/index.html',
  }),
  new webpack.DefinePlugin({
    'process.env': JSON.stringify(process.env),
  }),
],

config/jest.config.js

module.exports = {
  verbose: true,
  rootDir: '../',
  setupFiles: ['./config/jest.setup.js'],
  transform: {
    '^.+\\.js?$': 'babel-jest',
  },

config/jest.setup.js

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

jest error: ● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

...

Details:

/<...projectpath>/config/jest.setup.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Enzyme from 'enzyme';
                                                                                         ^^^^^^

SyntaxError: Unexpected token import

I want some a working test runner! Im guessing my transform: babel-jest is doing nothing in my jest.config.js...

like image 904
Nicholas Mueller Avatar asked Jan 31 '19 12:01

Nicholas Mueller


3 Answers

You need to do two things:

  1. Create a Babel config file (babel.config.js):

    This is necessary because babel-jest relies on a traditional Babel config file, not webpack. Since version 7 Babel has supported JS configs as babel.config.js.

    When using a JS Babel config (as opposed to a .babelrc, for example) Jest also compiles modules in node_modules. AFAIK by convention this must be in the root of your project, alongside the jest configuration file.

    Here is a config based on the Babel options in your webpack.config.js file:

    // babel.config.js
    module.exports = {
      presets: [
        '@babel/preset-env',
        '@babel/preset-react',
        '@babel/preset-flow',
      ],
      plugins: [
        'babel-plugin-styled-components',
        '@babel/plugin-proposal-class-properties',
      ]
    }
    
  2. Install the babel-core bridge version:

    npm install [email protected] --save-dev
    

    From github.com/babel/babel-bridge:

    This repo holds what we're calling a "bridge" package that is meant to ease the transition for libraries that use "babel-core" as a peer dependency for Babel 6.

    The issue with Babel 7's transition to scopes is that if a package depends on Babel 6, they may want to add support for Babel 7 alongside. Because Babel 7 will be released as @babel/core instead of babel-core, maintainers have no way to do that transition without making a breaking change. e.g.

like image 108
sdgluck Avatar answered Oct 25 '22 20:10

sdgluck


I ran into a similar situation where I wanted to test a React component .js file with jest, but it was failing because the component imported a .css stylesheet. I was using Babel with Webpack.

As per the accepted answer @sdgluck, I had to add a babel.config.js:

1.

module.exports = {
    presets: ['@babel/preset-env', '@babel/preset-react']
};

2. I also installed babel-jest as a dev-dependency

3. Then I read through the jest webpack guide

4. Which led me to adding a "jest" property to my package.json which mocks files and stylesheets:

"jest": {
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    }
  }

5. Then I had to create the mocked files at the specified paths (you can use any path you want, those are just from their docs):

// __mocks__/styleMock.js

module.exports = {};
// __mocks__/fileMock.js

module.exports = 'test-file-stub';

Then it worked :)

like image 25
mattyb Avatar answered Oct 25 '22 19:10

mattyb


I have some useful information that can be used as a reference for those who see this problem later.

By default, transformIgnorePatterns in jest config was ["/node_modules/", "\.pnp\.[^\/]+$"]

If some guys issue was caused by some code in node_modules and do not overwrite this value, babel-jest still not working.

Maybe the correct value like this "/node_modules/(?!(your-third-part-es-module-code|others-es-lib))"

like image 38
lemon Avatar answered Oct 25 '22 20:10

lemon