3

I try to use Jest with bablejs and ES2017 in my project, according to the Jest Getting Started page and also Bablejs config for ES2017 this is my .babelrc file :

{
  "presets": ["es2017"],
  "env": {
    "test": {
      "presets": ["es2017"]
    }
  }
}

And my package.json is:

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": ""
  },
  "homepage": "",
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-jest": "^21.2.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-es2017": "^6.24.1",
    "jest": "^21.2.1"
  }
}

When I type npm test to run all my test with jest i get these error :

 ){import StateList from './StateList';
                                                                                         
   ^^^^^^
  SyntaxError: Unexpected token import

It means it doesn't know import.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
MBehtemam
  • 7,865
  • 15
  • 66
  • 108

1 Answers1

6

babel-preset-es2017 does not transform import statements, because it only includes the plugins: syntax-trailing-function-commas and transform-async-to-generator.

When installing babel-preset-es2017 you also get a warning that it has been deprecated in favour of babel-preset-env, which contains everything that the es201x presets contained and more.

warning babel-preset-es2017@6.24.1:   Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!

As shown in the Migration guide from es2015 to env, it is a drop-in replacement.

npm install --save-dev babel-preset-env

And change your .babelrc to:

{
  "presets": ["env"]
}

Do not confuse babel-preset-env with Babel's env option, which I have removed from your current config, since you are using the exact same presets for the test environment as for any other, so it doesn't have any effect.

You can configure babel-preset-env to only transform features that are not supported by the platform you target, for example { "targets": { "node": "current" } } will only transform features that aren't supported by the Node version you are running. If no targets are specified, it will transform everything. For details see the Env preset documentation.

Note: With the upcoming version 7 of Babel, the official packages will be published under the namespace @babel, which means that babel-preset-env will be @babel/preset-env.

Michael Jungo
  • 31,583
  • 3
  • 91
  • 84