jest: Unexpected Token Import for ES6 modules

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
  }
}

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 51
  • Comments: 97 (8 by maintainers)

Commits related to this issue

Most upvoted comments

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"]
    }
  }
}

@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)

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.

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

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

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$"
}

@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.

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.

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 am having the same issue, the link @cpojer provided doesn’t seem to help 😕

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…

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

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

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",
}

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.

This will only help SOME people.

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

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!

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:

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

@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!

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

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…

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 babel-core@7.0.0-bridge.0 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.

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"]
}

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.

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"
}

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

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"],
    }
  }
}

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

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”

@cpojer 's fix worked for me, thanks

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/antd@4.6.1_react-dom@16.13.1+react@16.13.1/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)/)

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

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

package.json

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

Thanks kasvtv! Changed my .babelrc.js to .babelrc and installed npm i -D babel-core@7.0.0-bridge.0. Now my tests run with babel-jest

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.

@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)/"
]

@florentchauveau Thanks, this work for me.

@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

@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.

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.

This code helped me:

    "env": {
        "test": {
            "presets": [
                ["@babel/preset-env", {"targets": {"node": "current"}}]
            ]
        }
    }

where “test” - your enviroment

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

hope it helped!

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

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

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.

Adding

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

worked for me. Thanks to @rochapablo 🙌

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

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

@rochapablo in the same place. Any luck?