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)
See http://facebook.github.io/jest/docs/tutorial-react-native.html#transformignorepatterns-customization
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/
@calcazar what’s in your node_modules/enzyme/.babelrc?
I solved it by using babel-jest and ts-jest. In package.json:
Then in .babelrc (which I only use for testing)
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 😃
UPD1 Currently, my Jest config is:
… 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:
@jlyman
Based on the Jest doc, it should not be needed, since Jest sets the NODE_ENV to test by defult.
This .babelrc is what worked for me:
NOTE: it looks odd, but both development and test keys must be present, otherwise it will not work.
Then I just call:
or with package.json:
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 thetransformIgnorePatterns
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):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:
FWIW, I actually had the my
.babelrc
set up with the correctpresets
andplugins
under a test env like @cpojer had suggested, but had forgotten to includeNODE_ENV=test
on my scripts line inpackage.json
.Before, failing with “Unexpected token import”:
After, successfully transforming files:
Tried many things from the above discussion w.r.to
babel
configurations as well as some extra options from other search (such asesm
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:
In the
jest.config.js
file:Jest may complain about typescript not allowing
js
files to be complied. Add thetsconfig.json
file with below options:Removed all
babel
related configurations and files. Thenpm
configuration looks like below: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: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-stringThat is why any
import ...
will not work innode_modules
files. To disable this, you can add: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
jest.config.js
Dependencies:
babel-jest
@babel/plugin-transform-modules-commonjs
ts-jest
(for typescript)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
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:
.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 theunexpected token: import
for me.babel-7-jest
runs on an old Babel 7 core engine, thus breaking support for newer proposal plugins.npm i -D babel-core@7.0.0-bridge.0
FIXES THE ISSUE COMPLETELY. I don’t even haveenv.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: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
:package.json
: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:And I only needed to make sure that the “test” environment used modules instead:
"transform": { "^.+\\.js$": "babel-jest", "^.+\\.jsx?$": "babel-jest" },
add the above to jestI’m having the same issue. I added the following to my jest
and now I get the following error when I run Jest:
@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.See: https://regexr.com/5cs2h
https://jestjs.io/docs/en/tutorial-react-native#transformignorepatterns-customization
Fix
Use a negative lookahead for the last occurence by adding
.*
.adding
transformIgnorePatterns: []
to jest config andtransform-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
Thanks kasvtv! Changed my
.babelrc.js
to.babelrc
and installednpm i -D babel-core@7.0.0-bridge.0
. Now my tests run withbabel-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:
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:
@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:
where “test” - your enviroment
In my case,
.babelrc
is not work but I solved issue by moving same setting in.babelrc
tobabel.config.js
.hope it helped!
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
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?