jest: SyntaxError: Unexpected token import with babel-preset-env

  • you are using the latest version of Jest yes
  • try re-installing your node_modules folder yes
  • run Jest once with --no-cache to see if that fixes the problem you are experiencing yes

What is the current behavior?

imac:react-redux-test damz$ yarn test
yarn test v0.27.5
$ jest --no-cache --coverage
 FAIL  ./test.js
  ● Test suite failed to run

    /Users/damz/Desktop/react-redux-test/test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _cloneDeep from 'lodash-es/cloneDeep';function _asyncToGenerator(fn) {return function () {var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {function step(key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {return Promise.resolve(value).then(function (value) {step("next", value);}, function (err) {step("throw", err);});}}return step("next");});};}import { configure, shallow } from 'enzyme';
                                                                                             ^^^^^^
    
    SyntaxError: Unexpected token import
      
      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
          at Generator.next (<anonymous>)
          at Promise (<anonymous>)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.082s
Ran all test suites.
----------|----------|----------|----------|----------|----------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
----------|----------|----------|----------|----------|----------------|
All files |  Unknown |  Unknown |  Unknown |  Unknown |                |
----------|----------|----------|----------|----------|----------------|
error Command failed with exit code 1.

Repro? Repro here: https://github.com/damianobarbati/react-redux-test Simply clone, yarn install and yarn test.

Maybe this is due to latest babel-preset-env + browserslist?

"browserslist": [
    "chrome 58",
    "safari 10"
],
"babel": {
    "presets": [
        [
            "env",
            {
                "modules": false,
                "useBuiltIns": "usage",
                "debug": false
            }
        ],
        "stage-0",
        "react",
        "jest"
    ],
    "plugins": [
        "lodash",
        "transform-decorators-legacy",
        "transform-class-properties"
    ]
},
"jest": {
    "bail": true,
    "verbose": true
},
"dependencies": {
    "autobind-decorator": "2.1.0",
    "axios": "^0.16.2",
    "babel-eslint": "8.0.1",
    "babel-jest": "21.2.0",
    "babel-plugin-lodash": "3.2.11",
    "babel-plugin-transform-class-properties": "6.24.1",
    "babel-plugin-transform-decorators-legacy": "1.3.4",
    "babel-polyfill": "7.0.0-alpha.1",
    "babel-preset-env": "2.0.0-alpha.19",
    "babel-preset-react": "6.24.1",
    "babel-preset-stage-0": "6.24.1",
    "enzyme": "3.1.0",
    "enzyme-adapter-react-16": "1.0.1",
    "enzyme-to-json": "3.1.1",
    "eslint": "4.8.0",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jest": "21.2.0",
    "eslint-plugin-react": "^7.4.0",
    "jest": "21.2.1",
    "lodash-es": "4.17.4",
    "moxios": "0.4.0",
    "prop-types": "^15.6.0",
    "react": "16.0.0",
    "react-dom": "16.0.0",
    "react-redux": "^5.0.6",
    "react-test-renderer": "16.0.0",
    "recompose": "0.25.1",
    "redux": "^3.7.2",
    "redux-mock-store": "^1.3.0",
    "redux-promise": "0.5.3",
    "redux-thunk": "2.2.0"
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 29 (3 by maintainers)

Most upvoted comments

It seems like you aren’t including the ES module to commonjs transform. Please add that.

Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions. Thank you 😃

npm install --save-dev babel-jest

configuring jest as follows inside package.json solved the issue for me.

"jest": { "transform": { "^.+\\.jsx$": "babel-jest", "^.+\\.js$": "babel-jest" } }

“react-native”: “^0.50.1”, “jest”: “^21.2.1”, “babel-jest”: “^21.2.0”,

This minimal setup worked for me (jest w/ ES6):

.babelrc

{
  "env": {
    "test": {
      "presets": [
        ["env", { "modules": "commonjs" }]
      ]
    }
  }
}

package.json

{
  "devDependencies": {
    "babel-core": "^6.23.1",
    "babel-jest": "^22.4.3",
    "babel-preset-env": "^1.3.3",
    "jest": "^22.0.0"
  },
  "scripts": {
    "test": "NODE_ENV=test jest"
  },
  "engines": {
    "node": "^9.0.0"
  }
}

You need to setup "test" env in your babel config and configure babel-preset-env to use "modules": "commonjs". There’s a lot of examples in this issue tracker and in the wild.

For those like me…

Mind untranspiled imports from node_modules

Quite a few libraries ship nowadays with the module property set in package.json pointing at the untranspiled (es6, typescript) version of the library. Some bundlers use these by default.

However, as the docs state:

Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns to whitelist such modules. You’ll find a good example of this use case in React Native Guide.

And the solution given here:

"transformIgnorePatterns": [
  "node_modules/(?!(react-native|my-project|react-native-button)/)"
]

(goes in jest.config.js or jest key in package.json)

Having included the above, meant neither ["env", { "modules": "commonjs" }] in .babelrc nor any transfrom override in jest was needed.

I’ve been struggling with this for a few hours now, can anyone spot what I’m missing? I always get:

SyntaxError: Unexpected token import

Here are my config files below, using babel-jest to transpile .js files, and adding a “test” env in .babelrc.

package.json

{
   "scripts": { 
     "test:unit": "jest --config jest-config.js"
   },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-jest": "^22.0.3",
    "babel-preset-2017": "0.0.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "jest": "^22.0.3",
   }
}

jest-config.js

module.exports = {
  'rootDir': './',
  'verbose': true,
  'collectCoverage': true,
  'collectCoverageFrom': ['./**/*.js'],
  'coverageDirectory': '<rootDir>/coverage',
  'moduleFileExtensions': [
    'js'
  ],
  'transform': {
    '^.+\\.js$': 'babel-jest'
  },
  'coverageThreshold': {
    'global': {
      'branches': 70,
      'functions': 85,
      'lines': 85,
      'statements': 85
    }
  },
  'testResultsProcessor': './node_modules/jest-junit'
};

.babelrc

{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ]
  ],
  "env": {
    "test": {
      "presets": [
        [
          "env",
          {
            "modules": false
          }
        ]
      ]
    }
  }

Thanks for helping @thymikee, I realize this is not an help forum but I tried this configuration you mentioned here too https://github.com/facebook/jest/issues/4263#issuecomment-322045234

"babel": {
    "presets": [
        [
            "env",
            {
                "modules": false,
                "useBuiltIns": "usage",
                "debug": false
            }
        ],
        "stage-0",
        "react",
        "jest"
    ],
    "plugins": [
        "lodash",
        "transform-decorators-legacy",
        "transform-class-properties"
    ],
    "env": {
        "test": {
            "presets": [
                [
                    "env",
                    {
                        "modules": "commonjs",
                        "useBuiltIns": "usage",
                        "debug": false
                    }
                ],
                "stage-0",
                "react",
                "jest"
            ],
            "plugins": [
                "lodash",
                "transform-decorators-legacy",
                "transform-class-properties",
                "transform-es2015-modules-commonjs"
            ]
        }
    }
},

and a whole lot of other ones but it looks like they’re ignored. So I thought it was a problem of compatibility with latest babel-preset-env Thanks again for helping though : )

super minimal 😃 .babelrc { "presets": ["env"] }

modules: true in test, not false.

http://facebook.github.io/jest/docs/en/webpack.html#using-with-webpack-2

(PR welcome updating docs to use env instead of es2015)

got this issue also when i was optimizing my webpack. Fixed with the below config

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        modules: false
      }
    ],
    '@babel/preset-react'
  ],
  env: {
    test: {
      presets: [['@babel/preset-env', { modules: 'commonjs' }]]
    }
  },
  plugins: [
    '@babel/plugin-syntax-dynamic-import',
    'transform-react-remove-prop-types',
    [
      'transform-imports',
      {
        'react-router': {
          transform: 'react-router/${member}',
          preventFullImport: true
        }
      }
    ]
  ]
};

For me this only started happening after upgrading some dependencies, including babel-core (6.26.0->6.26.3) and babel-preset-env (1.6.1->1.7.0).

Simply installing babel-jest (23.6.0) solved it, with no configuration changes.

Edit: Upgrading jest from 22 to 23 works as well (without having to explicitly install babel-jest).