Liam Kenneth
Liam Kenneth

Reputation: 982

React Jest - Unexpected token import

I'm learning react and I want to test one of my components but I'm stuck with this error:

{import React from 'react';                                                                                   
^^^^^^
SyntaxError: Unexpected token import

Here's some things I have tried from reading post on stackoverflow and github

added test presets and these plugins "transform-es2015-modules-commonjs", dynamic-import-node" to my babel config

{
  "presets":  ["es2015", "react"],
  "env": {
  "test": {
      "presets":[
        ["es2015", { "modules": false }],
         "stage-0",
        "react"],
      "plugins": [
        "transform-es2015-modules-commonjs",
        "dynamic-import-node"
      ]
    }
}
}

In my package.json the Jest property has these settings:

"jest": {
    "verbose": true,
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "jsx",
      "js"
    ],
   "transform": {},
    "moduleDirectories": [
      "node_modules"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!react)/"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
  },

My actual component is built with ES6 and typescript if that helps you help me :)

From what I have read, it seems jest chokes on import because node doesn't understand ES6 import. None of the solutions I have tried online have seemed to work.

Also here are my dev Dependencies:

"devDependencies": {
    "awesome-typescript-loader": "^3.2.2",
    "babel-cli": "^6.24.1",
    "babel-core": "^6.25.0",
    "babel-eslint": "^7.2.3",
    "babel-jest": "^20.0.3",
    "babel-loader": "^7.1.1",
    "babel-plugin-dynamic-import-node": "^1.0.2",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.24.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^0.28.4",
    "enzyme": "^2.9.1",
    "eslint": "^4.4.1",
    "eslint-config-airbnb": "^15.1.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jsx-a11y": "^6.0.2",
    "eslint-plugin-react": "^7.2.0",
    "extract-text-webpack-plugin": "^3.0.0",
    "html-webpack-harddisk-plugin": "^0.1.0",
    "html-webpack-plugin": "^2.30.1",
    "jest": "^20.0.4",
    "node-sass": "^4.5.3",
    "react-test-renderer": "^15.6.1",
    "regenerator-runtime": "^0.10.5",
    "sass-loader": "^6.0.6",
    "source-map-loader": "^0.2.1",
    "style-loader": "^0.18.2",
    "ts-jest": "^20.0.10",
    "typescript": "^2.4.2",
    "webpack": "^3.5.1",
    "webpack-dev-middleware": "^1.12.0",
    "webpack-dev-server": "^2.7.0"
  },

Webpack config

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');

const HOST = "127.0.0.1";
const PORT = "9000";

const devServerUrl = "http://localhost:" + PORT + "/";

const config = {
  devtool: 'source-map',
  context: __dirname, // `__dirname` is root of project and `src` is source
  entry:
  [
    './src/index.js',
    './src/ui/styles.scss'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: "bundle.js",
    publicPath: ''
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css']
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
      { test: /\.js$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
      { test: /\.jsx$/, exclude: /node_modules/, loader: ['babel-loader', 'eslint-loader'] },
      {
        test: /\.(sass|scss)$/, use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  devServer: {
    contentBase: "dist/",
    noInfo: true,
    inline: true,
    compress: true,
    port: PORT,
    host: HOST,
    hot: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html', // Output file name.
      template: './public/index.html', // Use our HTML file as a template for the new one.
      inject: 'body',
      alwaysWriteToDisk: true,
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js'
      },
    }),
    new ExtractTextPlugin({ // define where to save the file
      filename: 'styles.bundle.css'}),
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackHarddiskPlugin({
  outputPath: path.resolve(__dirname, 'dist')
})
  ],
};

module.exports = config;

Thanks

Upvotes: 5

Views: 3837

Answers (3)

Liam Kenneth
Liam Kenneth

Reputation: 982

Jest doesn't work with Typescript.

I have removed Jest from my project and installed Mocha, Karma, Chai & Enzyme.

Effortless to set up compared to Jest which masquerades as a:

Zero configuration testing platform

This article was a huge help: Getting Started on Testing with Typescript, ReactJS, and Webpack.

Hopefully this will save others from wasting their time getting Jest to work with Typescript.

Upvotes: 3

davnicwil
davnicwil

Reputation: 31015

It's because you have configured babel to not transpile ES6 modules

  "presets":[
    ["es2015", { "modules": false }],

Try again with that modules to true (or omitted, since it defaults to true) and it should work.

Upvotes: 2

Vikram Saini
Vikram Saini

Reputation: 2769

you need to install babel to compile your es6 and react code

do it using

   C:\Users\username\Desktop\reactApp>npm install babel-core
C:\Users\username\Desktop\reactApp>npm install babel-loader
C:\Users\username\Desktop\reactApp>npm install babel-preset-react
C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015

Try to keep our webpack as

var config = {
   entry: './todoApp.js',

   output: {
      path:'./',
      filename: 'index.js',
   },

   devServer: {
      inline: true,
      port: 9191
   },

   module: {
         rules: [
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      }
      ],
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel',

            query: {
               presets: ['es2015', 'react']
            }
         }

      ]
   }
}

module.exports = config;

Upvotes: 0

Related Questions