Jest: Unexpected Token Import for ES6 modules

Created on 11 Nov 2016  ·  93Comments  ·  Source: facebook/jest

Do you want to request a feature or report a bug?
Report a bug

What is the current behavior?
I am using the same testing setup in several projects right now, all from my boilerplate. This problem has popped up in all of them recently, but I haven't yet been able to track it down. It seems that Jest is missing the babel configuration in my package.json and the test suite is failing with 'Unexpected Token Import'. Please keep in mind that up until a week ago, this configuration was working successfully in several projects, so I am assuming it's a regression and figured I should report it.

Note that when I add a .babelrc file the test suite passes for all but one test, where I get the same Unexpected Token Import, which seems bizarre considering there are a dozen passing tests that all use ES6 imports. Without the .babelrc all 14 tests are failing.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal repository on GitHub that we can npm install and npm test.

It can be reproduced from my boilerplate by installing npm run setup and running npm run test.

What is the expected behavior?
I expect that the Jest configuration that worked previously would still work. It would seem that my preprocessor is no longer running with babel-jest as it was previously.

Run Jest again with --debug and provide the full configuration it prints. Please mention your node and npm version and operating system.

jest version = 16.0.2
test framework = jasmine2
config = {
  "scriptPreprocessor": "/Users/myMac/Developer/works-in-progress/open-source-maintaining/scalable-react-boilerplate/config/testing/preprocessor.js",
  "moduleFileExtensions": [
    "js",
    "jsx",
    "json"
  ],
  "moduleDirectories": [
    "node_modules",
    "bower_components",
    "shared"
  ],
  "rootDir": "/Users/myMac/Developer/works-in-progress/open-source-maintaining/scalable-react-boilerplate",
  "name": "-Users-myMac-Developer-works-in-progress-open-source-maintaining-scalable-react-boilerplate",
  "setupFiles": [],
  "testRunner": "/Users/myMac/Developer/works-in-progress/open-source-maintaining/scalable-react-boilerplate/node_modules/jest-jasmine2/build/index.js",
  "automock": false,
  "bail": false,
  "browser": false,
  "cacheDirectory": "/var/folders/nq/7kdqy15d3m399326f7wtb_6w0000gn/T/jest",
  "clearMocks": false,
  "coveragePathIgnorePatterns": [
    "/node_modules/"
  ],
  "coverageReporters": [
    "json",
    "text",
    "lcov",
    "clover"
  ],
  "globals": {},
  "haste": {
    "providesModuleNodeModules": []
  },
  "mocksPattern": "__mocks__",
  "moduleNameMapper": {},
  "modulePathIgnorePatterns": [],
  "noStackTrace": false,
  "notify": false,
  "preset": null,
  "preprocessorIgnorePatterns": [
    "/node_modules/"
  ],
  "resetModules": false,
  "testEnvironment": "jest-environment-jsdom",
  "testPathDirs": [
    "/Users/myMac/Developer/works-in-progress/open-source-maintaining/scalable-react-boilerplate"
  ],
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.jsx?$",
  "testURL": "about:blank",
  "timers": "real",
  "useStderr": false,
  "verbose": null,
  "watch": false,
  "cache": true,
  "watchman": true,
  "testcheckOptions": {
    "times": 100,
    "maxSize": 200
  }
}

Most helpful comment

You are all likely running into this problem because ES modules are not supported in Node and you deliberately stopped compiling them with your build pipeline (webpack, rollup) when you are shipping them to the browser.

You need to enable compilation from ES modules to CommonJS for the "test" env in your babelrc, see https://babeljs.io/docs/usage/babelrc/#env-option and https://babeljs.io/docs/plugins/transform-es2015-modules-commonjs/

{
  "env": {
    "production": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

All 93 comments

I have this same issue with React-Native and Jest,
If you start a new project with:
react-native init AwesomeProject
cd AwesomeProject

then install a module like npm install native-base --save
import any component from native-base into your index.ios.js file

npm test will throw this error:
../test/node_modules/native-base/index.js:4
import Drawer from './Components/vendor/react-native-drawer';
^^^^^^
SyntaxError: Unexpected token import

I am having the same issue, the link @cpojer provided doesn't seem to help 😕

Hi! 'transformIgnorePatterns' does....mmmm...that it must does - ignoring)
But how I can use that import in package from node_modules?

This props helped me :)

{
  "jest": {
    "verbose": true,
    "moduleDirectories": ["node_modules", "src"]
  },
}

UPD1
Currently, my Jest config is:

"jest": {
    "verbose": true,
    "transform": {
      "^.+\\.js$": "babel-jest",
      "^.+\\.(css|scss|less)$": "jest-css-modules"
    },
    "globals": {
      "NODE_ENV": "test"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules",
      "src/frontend",
      "src/shared"
    ]
  },

... and it's working for me :)

Best regards, Pavel Tretyakov

Hi guys, I am still hacing this problem, but I am not using react native. The problem is always fixed using jest --no-cache. Is there a way to make jest work using cache, without throwing this error?

I cannot get this transform to work with my create-react-app application. Always get "Unexpected token import" on any test files containing ES6 import. I've tried all suggestions I could find. no-cache has no impact. I obviously can't ignore these files from the transform (they need to be transformed!).

I give up. Happy to provide any required information.

I seem to also be experiencing this issue.

Same here

Same here

You are all likely running into this problem because ES modules are not supported in Node and you deliberately stopped compiling them with your build pipeline (webpack, rollup) when you are shipping them to the browser.

You need to enable compilation from ES modules to CommonJS for the "test" env in your babelrc, see https://babeljs.io/docs/usage/babelrc/#env-option and https://babeljs.io/docs/plugins/transform-es2015-modules-commonjs/

{
  "env": {
    "production": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

Thanks for your response, cpojer. Yesterday I removed my node env settings and let it ran with default node env, because jest was working globally, but not while using node scripts. It seemed to solve the issue, so I believe that my problem was with node-env settings. But it is still something to monitor.

EDIT: This did not work at all. @cpojer's fix worked like a charm. Thanks.

@cpojer 's fix worked for me, thanks

Awesome, also worked for me, thanks!

I am having a similar issue in my fairly simple react native app.

When running npm test or jest this is returned 'SyntaxError: Unexpected token import'

.babelrc

{
"presets": ["react-native"]
}

.package.json

{
  "name": "BeeAppy",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "babel-jest": "^20.0.3",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-native": "^2.0.0",
    "enzyme": "^2.8.2",
    "eslint": "^4.0.0",
    "eslint-plugin-react": "^7.1.0",
    "jest": "^20.0.4",
    "react-addons-test-utils": "^15.6.0",
    "react-dom": "^15.6.1",
    "react-test-renderer": "^16.0.0-alpha.6"
  },
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "test": "node node_modules/jest/bin/jest.js --watch"
  },
  "jest": {
    "preset": "react-native"
  },
  "dependencies": {
    "react": "16.0.0-alpha.6",
    "react-native": "^0.44.0",
    "react-navigation": "^1.0.0-beta.11"
  }
}

Does the env snippet suggested by @cpojer go in the .package.json?
Sorry if it is really obvious!
Any help would be great, thanks

@JessicaBarclay it should go in your .babelrc config. Like this:

"env": {
          "development": {
                 "plugins": ["transform-es2015-modules-commonjs"]
          }
}

Ahh Thank you @rlage ! Sorted :)

FWIW, I actually had the my .babelrc set up with the correct presets and plugins under a test env like @cpojer had suggested, but had forgotten to include NODE_ENV=test on my scripts line in package.json.

Before, failing with "Unexpected token import":

"scripts": {
  ...
  "test": "jest",
}

After, successfully transforming files:

"scripts": {
  ...
  "test": "NODE_ENV=test jest",
}

@jlyman

Based on the Jest doc, it should not be needed, since Jest sets the NODE_ENV to test by defult.

Note: If you are using a more complicated Babel configuration, using Babel's env option, keep in mind that Jest will automatically define NODE_ENV as test. It will not use development section like Babel does by default when no NODE_ENV is set.

This .babelrc is what worked for me:

{"env": {
    "development": {
        "plugins": ["transform-es2015-modules-commonjs"]
    },
    "test": {
        "plugins": ["transform-es2015-modules-commonjs"]
    }
}}

NOTE: it looks odd, but both development and test keys must be present, otherwise it will not work.

Then I just call:

node_modules/.bin/jest

or with package.json:

{"scripts": {"test": "jest"}}

No need for setting NODE_ENV to test.

@laszbalo Interesting, the presence of that second env does seem to do the trick. If I add in a development environment and take out the explicit NODE_ENV prefix on my scripts it works. I had read that part of the docs too, but ended up with that solution since it worked.

@jlyman which solution in docs?

@doudounannan Sorry if that wasn't clear. The solution I ended up going with was what I posted here. Like @laszbalo said, it goes against what the docs say under Using Babel, but either @laszbalo's solution or my direct injection of NODE_ENV test seem to work.

Strangely when I use "transformIgnorePatterns": [ ] then babel transforms my tested files, but if I exclude the transformIgnorePatterns option then babel doesn't do anything... I have a simple .babelrc for testing only (I use webpack for production, but not for jest's tests):

{
  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

I got the idea from https://github.com/facebook/jest/issues/2550#issuecomment-290812720 since nothing else in #770 or here seemed to help...

Doesn't matter what I do, it's always the same error:

    /.../node_modules/@expo/react-native-action-sheet/ActionSheet.ios.js:3
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
      at Object.<anonymous> (node_modules/@expo/react-native-action-sheet/index.js:1:107)
      at Object.<anonymous> (node_modules/react-native-gifted-chat/src/GiftedChat.js:10:29)
{
  "env": {
    "production": {
      "plugins": ["transform-es2015-modules-commonjs"]
    },
    "development": {
      "plugins": ["transform-es2015-modules-commonjs"]
    },
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  },
  "presets": [
    "react-native"
  ],
  "plugins": [
    ["module-resolver", {
            "cwd": "babelrc",
        }]
  ]
}
"jest": {
    "preset": "react-native",
    "setupFiles": [
        "./__tests__/setup.js"
    ],
    "testRegex": "/__tests__/.*\\.spec\\.js$"
}

I'm having the same issue. I added the following to my jest

"jest": {
     "preset": "react-native",
     "transformIgnorePatterns": [
          "node_modules/(?!react-native|react-navigation)/"
      ]
  }

and now I get the following error when I run Jest:

ReferenceError: Unknown plugin "transform-replace-object-assign" specified in "/Users/caalcaz/Documents/Projects/Enterprise-app/node_modules/enzyme/.babelrc" at 0, attempted to resolve relative to "/Users/caalcaz/Documents/Projects/Enterprise-app/node_modules/enzyme"

@calcazar what's in your node_modules/enzyme/.babelrc?

I solved it by using babel-jest _and_ ts-jest. In package.json:

"jest": {
    "modulePaths": [
        "<rootDir>/src",
        "<rootDir>/node_modules"
    ],
    "globals": {
        "NODE_ENV": "test"
    },
    "verbose": true,
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "jsx",
        "json"
    ],
    "transform": {
        "^.+\\.jsx?$": "babel-jest",
        "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "transformIgnorePatterns": ["/node_modules/(?!lodash-es)"], // <-- this allows babel to load only the node modules I need (which is lodash-es) and ignore the rest
    "testRegex": "test/.*\\.spec\\.ts$",
    "setupFiles": [
        "<rootDir>/test/jest-pretest.ts"
    ],
    "testEnvironment": "node",
    "moduleNameMapper": {
        "aurelia-(.*)": "<rootDir>/node_modules/$1"
    },
    // some coverage and results processing options
},

Then in .babelrc (which I only use for testing)

{
    "env": {
        "test": {
        "plugins": ["transform-es2015-modules-commonjs"]
        }
    }
}

hope that helps someone! (This is for an aurelia app so YMMV)

@thinkOfaNumber

This is what I see. as an FYI I'm running Enzyme V3.0

{
  "presets": ["airbnb"],
  "plugins": [
    ["transform-replace-object-assign", "object.assign"],
  ],
}

@thinkOfaNumber thank you for posting your suggestion. I used it to figure out how to get es6 modules from an external library to get compiled in jest. The key is here

"jest": {
    "modulePaths": [
        "<rootDir>/src",
        "<rootDir>/node_modules"
    ],
    "transformIgnorePatterns": ["/node_modules/(?!lodash-es)"], // <-- this allows babel to load only the node modules I need (which is lodash-es) and ignore the rest

This is the part that I need it. Thank you so much!

@rochapablo in the same place. Any luck?

Noop, for now I'm ignoring the specific file test that throw the error

Following. I have the same issue and nothing so far seems to resolve it.

Following too

@rochapablo Have You succeded resolving this issue?
I'm also can't test component that has GiftedChat as a child because of issue You mentioned...

@todorone, try to add:

"transformIgnorePatterns": [
      "node_modules/(?!react-native-gifted-chat)/"
]

@rochapablo Thanks for the hint, but unfortunately it didn't help. I even tried to play further with transformIgnorePatterns regexes but it didn't help.

"transform": { "^.+\\.js$": "babel-jest", "^.+\\.jsx?$": "babel-jest" },
add the above to jest

@rochapablo Have you tried the jest-expo preset? Any luck? I ran into another syntax problem with it & transformIgnorePatterns

Still doesn't work for me. I get the damn import error.
image

@testacode that's a dynamic import, have you added the necessary babel plugin? See bottom of https://facebook.github.io/jest/docs/en/webpack.html#using-with-webpack-2

@SimenB thanks, that's what I was missing!

It's interesting. Some recent update removed automatic adding of babel-jest. So running:

npm install babel-jest --save-dev

and adding NOTHING ELSE in config fixed the issue for me. I think it should be more clear in an error message that it is no longer included...

I solved just by installing babel-jest:
npm i babel-jest

Also, do not forget to create a .babelrc file with the following content:

{
    "presets": ["env", "react"]
}

This works for me:

.babelrc:

{
    "presets": ["env", "stage-3"],
    "plugins": ["transform-class-properties"]
}

package.json:

"scripts": {
    "test": "jest --forceExit"
},
"devDependencies": {
    "babel-core": "^6.11.4",
    "babel-jest": "^21.2.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-3": "^6.24.1",
    "jest": "^21.2.0"
}

@hqro it worked for me, Thanks 👍

For me, I had this in my .babelrc file:

{
  "presets": ["react", ["env", { "modules": false }]],
  "plugins": [ ... ]
}

And I only needed to make sure that the "test" environment used modules instead:

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

@nemoDreamer It's better to not repeat plugins and presets in one config

{
  "presets": ["react", ["env", { "modules": false }]],
  "plugins": [ ... ],
  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"],
    }
  }
}

Whatever I try, I got an error.

> cross-env NODE_ENV=test jest --no-cache

 FAIL  src\views\Pay\__tests__\Pay.test.js
  ● Test suite failed to run

    C:\Users\***\Documents\Project\***\node_modules\ne-rc\lib\index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _Alert from './Alert';
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      11 |  * @param {Array<Object>} [data] 每一种分期的详细信息 data=[{},{}...]
      12 |  * @param {Number} [defaultSelected] 默认选中的下标
    > 13 |  * @param {Funtion} [onClick] 点击触发事件
      14 |  * @param {Number} [columnNum] 一行有多少列
      15 |  *
      16 |  * @example

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
      at Object.<anonymous> (src/components/Installment/Installment.jsx:13:13)
      at Object.<anonymous> (src/components/Installment/index.js:8:20)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.693s

Here is my config files.

* .babelrc *

{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ],
    // webpack understands the native import syntax, and uses it for tree shaking

    "es2015",
    "stage-2",
    // Specifies what level of language features to doPay.

    // Stage 2 is "draft", 4 is finished, 0 is strawman.

    // See https://tc39.github.io/process-document/

    "react"
    // Transpile React components to JavaScript
  ],
  "env": {
    "test": {
      "presets": ["env", "react", "stage-2"],
      "plugins": [
        "transform-es2015-modules-commonjs"
      ]
    }
  }
}

package.json

{
  "main": "index.js",
  "scripts": {
    "dev": "cross-env NODE_ENV=development node ./server/server.js",
    "api": "cross-env NODE_ENV=api node ./server/server.js",
    "clean": "rm -rf dist",
    "dist": "npm run clean && cross-env NODE_ENV=production webpack --config ./webpack/index.js --progress --colors",
    "online": "cross-env NODE_ENV=development node ./server/online.js",
    "lint": "node ./node_modules/eslint/bin/eslint.js ./src --fix",
    "test": "cross-env NODE_ENV=test jest --no-cache",
    "test:watch": "npm test --watch",
    "stats": "npm run clean && cross-env NODE_ENV=production webpack --config ./webpack/index.js --profile --json > stats.json",
    "gatest": "node ./service/gatest.js"
  },
  "pre-commit": [
    "lint"
  ],
  "jest": {
    "verbose": true,
    "modulePaths": [
      "<rootDir>/src",
      "<rootDir>/node_modules"
    ],
    "setupFiles": [
      "./test/setup.js"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "md"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
    ],
    "transform": {
      "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "testEnvironment": "jsdom"
  },
  "devDependencies": {
    "asset-inject-html-webpack-plugin": "^0.9.1",
    "autoprefixer": "^7.1.3",
    "babel": "^6.23.0",
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.2.1",
    "babel-jest": "^22.4.1",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-jest": "^22.4.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "babel-register": "^6.26.0",
    "better-npm-run": "0.1.0",
    "body-parser": "^1.17.2",
    "chalk": "^2.1.0",
    "cross-env": "^5.0.5",
    "css-loader": "^0.28.5",
    "deepmerge": "^2.0.1",
    "enzyme": "^3.3.0",
    "eslint": "^4.5.0",
    "eslint-config-standard": "^11.0.0-beta.0",
    "eslint-config-standard-jsx": "^4.0.2",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-node": "^5.1.1",
    "eslint-plugin-promise": "^3.5.0",
    "eslint-plugin-react": "^7.3.0",
    "eslint-plugin-standard": "^3.0.1",
    "exports-loader": "^0.6.4",
    "express": "^4.15.4",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^1.1.6",
    "git-repo-info": "^1.4.1",
    "glob": "^7.1.2",
    "happypack": "^4.0.1",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "idb": "^2.0.4",
    "imports-loader": "^0.7.0",
    "jest": "^22.4.2",
    "lodash.range": "^3.2.0",
    "mocha": "^5.0.0",
    "node-sass": "^4.5.3",
    "node-xlsx": "^0.11.2",
    "postcss-loader": "^2.0.6",
    "pre-commit": "^1.2.2",
    "react-hot-loader": "^3.0.0-beta.6",
    "react-test-renderer": "^16.2.0",
    "redux-logger": "^3.0.6",
    "regenerator-runtime": "^0.11.1",
    "request": "^2.74.0",
    "require-reload": "^0.2.2",
    "rimraf": "^2.6.0",
    "sass-loader": "^6.0.6",
    "script-loader": "^0.7.0",
    "sinon": "^4.2.0",
    "style-loader": "^0.19.1",
    "uglify-js": "^3.0.28",
    "url-loader": "^0.6.2",
    "webpack": "^3.5.5",
    "webpack-bundle-analyzer": "^2.9.0",
    "webpack-dev-middleware": "^2.0.4",
    "webpack-dev-server": "^2.7.1",
    "webpack-hot-middleware": "^2.18.2",
    "webpack-merge": "^4.1.0",
    "worker-loader": "^1.1.0"
  }
}

When setting the preset in .babelrc, make sure "env" is between brackets ["env"], like this:

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

especially if you have "modules: false" in your configuration.

Also, by default, jest does NOT transform files in node_modules, cf https://facebook.github.io/jest/docs/en/configuration.html#transformignorepatterns-array-string

That is why any import ... will not work in node_modules files. To disable this, you can add:

transformIgnorePatterns: []

to your jest config.

Hope this helps!

@florentchauveau Thanks, this work for me.

@todorone @rochapablo Did you guys find a solution for this? Even I'm facing the same issue-

    import * as React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
      at Object.<anonymous> (node_modules/@expo/react-native-action-sheet/index.js:1:107)

I'm getting this error only on the tests of the components using
GiftedChat - https://github.com/FaridSafi/react-native-gifted-chat.
Maybe this is because @expo/react-native-action-sheet is being shipped as an ES6 module and GiftedChat is internally using it? But jest/ts-jest (I'm not sure) should handle that if the presets are added. Here is my Jest config -

    "jest": {
        "preset": "react-native",
        "moduleFileExtensions": [
            "ts",
            "tsx",
            "js"
        ],
        "transform": {
            "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
            "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
        },
        "transformIgnorePatterns": [
            "node_modules/(?!rn-placeholder|react-native|react-navigation|native-base|react-native-datepicker|native-base-shoutem-theme|@shoutem/animation|@shoutem/ui|tcomb-form-native)"
        ],
        "setupTestFrameworkScriptFile": "<rootDir>/src/__mocks__/Adapter.js",
        "testRegex": "(\\.(test|spec))\\.(ts|tsx|js)$",
        "testPathIgnorePatterns": [
            "\\.snap$",
            "<rootDir>/node_modules/",
            "<rootDir>/lib/"
        ],
        "moduleNameMapper": {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.js"
        },
        "cacheDirectory": ".jest/cache"
    },

and the .babelrc -

{
    "presets": ["react-native"]
}

I've tried almost all the solutions mentioned above. None of them worked in my scenario. Help needed.

@omkarjoshi-cc the only thing that worked for me at the time that I was working on, was add the package that was firing the error, which in my case was:

"transformIgnorePatterns": [
      "node_modules/(?!react-native-gifted-chat)/"
]

@rochapablo Yeah. I tried it. Didn't work. Is there any other thing that might be missing out? This is really frustrating 😓

I'm using babel 7 and me too still had no luck with "transformIgnorePatterns" - tried many different regular expressions :/

The issue I have is that one dependency has native es6 classes in it, and I have a class in my source that extends it. Since "es5 classes" transpiled by Babel cannot extend a native class, I get a runtime error in jest.

I started to think that somehow "babel/preset-env" is getting in the way of how the code is transpiled to jest (target node), which might not follow the browser targets, but still not sure about that.

Does any one know how to force everything to es5 for jest when using 'present-env' in .babelrc?

The only workaround I can think is to not use babel-jest, run through webpack (which uses babel-loader, and the rules to which files to transform worked for me), then run jest -> I am thinking about using webpack -w and jest watch the transpiled..)

Adding

"transformIgnorePatterns": [
      "node_modules/(?!react-native-gifted-chat|@expo/react-native-action-sheet)"
]

worked for me. Thanks to @rochapablo 🙌

I'm struggling with this issue. Should my output folder which is being tested be ES6 syntax with import etc or can jest not test that? I'm not seeing any commonjs in my output file/files (using it with react-native)

i'm facing the same issue and this page solve the problem :
https://babeljs.io/docs/plugins/transform-es2015-modules-commonjs/

For some reason, instead of babel-jest, using the following made it work for me (respect the transformIgnorePatterns apparently)

"transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "ts-jest-babel-7"
    }

btw this issue should be re-opened here right? many people facing difficulties

In my case it turns out this problem was caused by ignoring test files in my babel config. For unrelated reasons I had "ignore": ["**/*.test.js"] in my .babelrc.

The solution was to only set the ignore option for the production environment, i.e:

"env": {
    "production": {
      "ignore": [
        "**/*.test.js"
      ]
    }
  }

Alternatively, you could specify a special ignore pattern for the test env.

After triying a lot, here is my case

  1. Make sure to have the right versions of babe-jest *
  2. make sure to have .babelrc configuration with presets(previously installed)
  3. if its still thrown error of "unexpected token" maybe are arrow functions not recongnized, this babel plugin will help you "transform-class-properties" also include them on your babel config.

here are my configs.

.babelrc

{
  "plugins": [
    "transform-es2015-modules-commonjs",
    "transform-class-properties"
  ]}

for enzyme(setupTests.js)

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-15";
configure({ adapter: new Adapter() });

package.json

 "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "eslint": "^4.19.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-test-renderer": "^15.6.2",
     "babel-jest": "^22.4.3",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-15": "^1.0.5",
    "gh-pages": "^0.12.0",
    "jest": "^22.4.3",
    "react-addons-test-utils": "^15.4.2",
    "regenerator-runtime": "^0.11.1"
  },
"jest": {
    "globals": {
      "NODE_ENV": "test"
    },
    "verbose": true,
    "moduleDirectories": ["node_modules", "src"],
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    },
    "moduleFileExtensions": ["js", "jsx"],
    "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js"
  }

yarn add --dev babel-jest babel-core regenerator-runtime adding this worked for me

In my case, it was a problem with windows and its stupid permissions, probably not setting correctly the env variables.
Switched from git bash to an elevated cmd.exe and started working again.

I have jest defined as a script (renamed test:jest as test), in my package.json. However, when running npm run test, I get SyntaxError: Unexpected token import:

root@browserify:/var/machine-learning/src# npm run test

> [email protected] test /var/machine-learning/src
> jest --config /var/machine-learning/test/jest/jest.config.js

 FAIL  ../test/jest/__tests__/layout/analysis.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/layout/analysis.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/layout/page.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/layout/page.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/content/register.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/content/register.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/content/login.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/content/login.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |        0 |        0 |        0 |        0 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 4 failed, 4 total
Tests:       0 total
Snapshots:   0 total
Time:        3.782s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: `jest --config /var/machine-learning/test/jest/jest.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-05-08T01_50_42_754Z-debug.log

I also defined a corresponding jest.config.js:

module.exports = {
  'verbose': true,
  'collectCoverage': true,
  'coverageDirectory': '/var/machine-learning',
  'moduleDirectories': ['/var/machine-learning/src/node_modules'],
  'transformIgnorePatterns': [
    '/var/machine-learning/src/node_modules'
  ]
}

I'm seeing a lot of things about react-native, and transformIgnorePatterns. Luckily, and unluckily, I don't use that. What an elusive bug this is. Do I need to define .babelrc, or add a jest directive in my package.json. How does my jest script know about babel, if this is the case? I've tried to add a .babelrc, in the same directory containing my package.json, with no luck:

{
  "env": {
    "test": {
      "presets": ["env", "stage-2", "react"]
    }
  }
}

Note: if anyone wants to keep track of my original issue regarding the above problem.

After lots of fooling around, I've found the following issues:

  • Jest runs babel 6 by default. Babel 6 doesn't look for a .babelrc.js file. Only for a .babelrc file. If you have a JS config instead of JSON, it won't read the config and thus not use any plugins. This resulted in the unexpected token: import for me.
  • babel-7-jest runs on an old Babel 7 core engine, thus breaking support for newer proposal plugins.
  • It seems that npm i -D [email protected] FIXES THE ISSUE COMPLETELY. I don't even have env.test in my babel config, nor do I have any jest config.

It seems as though Jest looks for babel-core (and thus ignores @babel/core), otherwise it falls back to Babel 6 and skips your config. But when the latest babel-core (bridge version) is installed it parses ES6 modules without any extra config.

Thanks kasvtv! Changed my .babelrc.js to .babelrc and installed npm i -D [email protected]. Now my tests run with babel-jest

You can safely use a .js config file. It's just that Babel only reads this type of file from version 7 onwards and you need [email protected] for Jest to use version 7 of Babel.

If anyone is interested, I got my jest + enzyme tests working. Feel free to poke into corresponding configuration files. Also, is anyone interested helping out on frontend development for that same project?

Had a similar problem due to antd and rc-calendar etc. libraries failing to import modules, solution was to configure transformIgnorePatterns

transformIgnorePatterns: [ 'node_modules/?!(antd|rc-.+)/' ],

Maybe moduleDirectories helped as well:

moduleDirectories: ['node_modules'],

I updated to latest react-native version and had to update to babel 7 and i now get the same error.

Adding these node_modules into transformIgnorePatterns does not seem to do anything anymore.

In my case, it's because I'm no longer transpiling modules with Babel, and there's a note on the getting started guide about adding that back in to the test portion of your babelrc.

@kasvtv @willb335 I use a trick to get Babel 6 to recognize .babelrc.js:

package.json

  "babel": {
    "presets": [
      "./.babelrc.js"
    ]
  },

I meet the same issue with use @material/base library, could anyone provide package.json & .babelrc file to solve. I try above feedbacks, but I mixed up...

the solution for me was adding "env" preset on .babelrc file so it turned out like this
{
"presets": ["env", "es2016", "stage-0", "react"]
}

Using this link info solved my problem
https://jestjs.io/docs/en/webpack.html

@negarineh your link does not work

Using the transformIgnorePatterns solution provided by @haywirez turns my

SyntaxError: Unexpected token import

error into an

TypeError: Cannot read property 'DocumentDir' of undefined

errror. I.e. the package (rn-fetch-blob) is now undefined.

Edit:

actually just adding transformIgnorePatterns: [], to my jest.config.js causes the SyntaxError to chage to the TypeError.

@schumannd Sorry I made a mistake, the link is redirecting you to the page now. If you set your "jest.config.js" with the configuration that provided in the link it should work.
If the error is about importing .css file adding a mock file like the example in the link or just by installing "identity-obj-proxy" with this configuration should work:

npm install --save-dev identity-obj-proxy

jest.config.js (for CSS Modules):

{ "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)$": "identity-obj-proxy" } } }

Also, this is my .babelrc file in the root directory of the project( test.config.js also should be in the root):

First, to use babel install "babel-jest" and "regenerator-runtime":

npm --dev babel-jest babel-core regenerator-runtime

Then add this configuration to .babelrc file:

{ "presets": ["env", "react"], "plugins": ["transform-class-properties"], "env": { "production": { "plugins": ["transform-es2015-modules-commonjs"] }, "test": { "presets": ["env", "react"], "plugins": ["transform-export-extensions"], "only": [ "./**/*.js", "node_modules/jest-runtime" ] } } }

Hope this helps.
https://jestjs.io/docs/en/webpack.html

In my case, it works after adding the following .babelrc

{
  "presets": ["env", "react"],
  "env": {
    "test": {
      "plugins": ["transform-class-properties"]
    }
  }
}

and then run test using NODE_ENV=test jest

This will only help SOME people.

My issue was due to jest not being able to parse my JS file. I used require instead.

Guys. None of these solutions work because I dont have a a babelrc file... only babel.config.js. Please, how do you fix with babel.config.js? Thanks

Tried many things from the above discussion w.r.to babel configurations as well as some extra options from other search (such as esm options) - nothing worked. The import keyword continued to give error from jest. It is sad that testing a module with es6 imports is so hard.

Finally this is what worked for me: ts-jest

Now, I am not using any typescript in my code as such, yet used the ts-jest all the same (since typescript internally has support for imports and all other things). This is just to make the jest understand the javascript code properly.

Followed these steps:
npm i -D jest typescript ts-jest @types/jest
In the jest.config.js file:
transform: { "\\.js$": "ts-jest", transformIgnorePatterns: [], },
Jest may complain about typescript not allowing js files to be complied. Add the tsconfig.json file with below options:
{ "compilerOptions": { "allowJs": true, "module": "commonjs", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "sourceMap": true } }
Removed all babel related configurations and files. The npm configuration looks like below:
"scripts": { "test": "jest --runInBand --detectOpenHandles --no-cache --config ./jest.config.js" }
Hope this helps anyone facing similar problem with imports.

Does anyone have a bare bones repo which has a working setup using JS imports?

Does anyone have a bare bones repo which has a working setup using JS imports?

https://github.com/kasvtv/react-starter

As someone who found this page while searching for a similar issue that is likely irrelevant to the original discussion. My issue ended up being due to using the function-like dynamic imports described by https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports. This ended up being solved by adding the babel plugin for this feature available at https://github.com/airbnb/babel-plugin-dynamic-import-node and modifying the .babelrc accordingly.

{
    ...
    "env": {
        "test": {
            "plugins": ["dynamic-import-node"]
        }
    ...
}

i just remove the option :{ module:false }, and then it works

"presets": [
    ["@babel/env", {module: false} ],  
    "@babel/preset-react",
    "@babel/preset-typescript"
  ]

adding transformIgnorePatterns: [] to jest config and transform-es2015-modules-commonjs to babelrc solved the issue for me.
jest: ^23.1.0,
babel: 6.26.3

@ngmgit but this means that you transpile all your node_modules, which is not very optimal...

In my case,
.babelrc is not work but I solved issue by moving same setting in .babelrc to babel.config.js.

hope it helped!

None of EVERYTHING that is on here works to me. I cant believe that a facebook`s official testing library to test React applications is that level of hard to configure, i am a developer with 8+ years of experience and i spent 5 hours of my day without success going trhough so many issues and questions on stack overflow.

i just cant configure my react application to work with jest + react-testing-library

this is ONLY because jest is yelling every time to me a new syntax error that he cant proccess. Every plugin i use solve one problem and give another one. There is way to make babel handle everything?

I am sincerely done with that i really given up, i am no longer spending more time on that, i will probably cancel adding this library on the project.

Seriously, it is very weird to see that there is NO default configuration for ANYONE that wants to test a react application using jest + react-testing-library.

after hours of trial and error with many a SO answer and github issue, @cpojer's answer worked for me! 🙏

UPDATED with latest and greatest with some additional context that helped me:

babel.config.js

module.exports = {
  "env": {
    "production": {
-      "plugins": ["transform-es2015-modules-commonjs"]
# new kid on the block
+      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
  }
}

jest.config.js

module.exports = {
  // if you're also using typescript
  preset: "ts-jest",
  testEnvironment: "node",
  verbose: true,
  // registers babel.config.js with jest
  transform: {
    "^.+\\.js$": "babel-jest",
  },
  // explicitly include any node libs using ESM modules
  transformIgnorePatterns: ["node_modules/?!(<ESM module here>|<another here>|<etc...>)"],
}

Dependencies:

This issue can also happen when not running jest in the project's root directory...

If you are using react-native or jest-expo presets and have .js files in your project, you should set transform to match it in jest config.
I used an expression from https://jestjs.io/docs/en/configuration.html#transform-objectstring-pathtotransformer--pathtotransformer-object and it worked.

transform: { '^.+\\.[jt]sx?$': 'babel-jest' }

pnpm support

I want to leave a note here for pnpm users....

The following example doesn't work for pnpm users because pnpm paths are different. The above regexes only work with flattened node_modules dirs.

/xxx/node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/antd/es/input/String

See: https://regexr.com/5cs2h

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

https://jestjs.io/docs/en/tutorial-react-native#transformignorepatterns-customization

Fix

Use a negative lookahead for the last occurence by adding .*.

node_modules/(?!(.*antd/es)/)
Was this page helpful?
0 / 5 - 0 ratings