New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected Token Import for ES6 modules #2081

Closed
RyanCCollins opened this Issue Nov 11, 2016 · 83 comments

Comments

Projects
None yet
@RyanCCollins
Copy link

RyanCCollins commented Nov 11, 2016

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

This comment has been minimized.

Copy link

Maftalion commented Nov 11, 2016

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

@cpojer

This comment has been minimized.

@cpojer cpojer closed this Nov 14, 2016

@fuyi

This comment has been minimized.

Copy link

fuyi commented Feb 4, 2017

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

@DmitrySkripunov

This comment has been minimized.

Copy link

DmitrySkripunov commented Feb 7, 2017

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

@ptretyakov

This comment has been minimized.

Copy link

ptretyakov commented May 10, 2017

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

@rlage

This comment has been minimized.

Copy link

rlage commented May 25, 2017

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?

@danderson00

This comment has been minimized.

Copy link

danderson00 commented May 31, 2017

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.

@joshjung

This comment has been minimized.

Copy link

joshjung commented Jun 1, 2017

I seem to also be experiencing this issue.

@miketeix

This comment has been minimized.

Copy link

miketeix commented Jun 5, 2017

Same here

1 similar comment
@dangreenisrael

This comment has been minimized.

Copy link

dangreenisrael commented Jun 7, 2017

Same here

@cpojer

This comment has been minimized.

Copy link
Contributor

cpojer commented Jun 7, 2017

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

This comment has been minimized.

Copy link

rlage commented Jun 7, 2017

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.

@Pr0x1m4

This comment has been minimized.

Copy link

Pr0x1m4 commented Jun 17, 2017

@cpojer 's fix worked for me, thanks

@nighto

This comment has been minimized.

Copy link

nighto commented Jun 21, 2017

Awesome, also worked for me, thanks!

@JessicaBarclay

This comment has been minimized.

Copy link

JessicaBarclay commented Jun 22, 2017

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

@rlage

This comment has been minimized.

Copy link

rlage commented Jun 22, 2017

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

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

This comment has been minimized.

Copy link

JessicaBarclay commented Jun 22, 2017

Ahh Thank you @rlage ! Sorted :)

@jlyman

This comment has been minimized.

Copy link

jlyman commented Jun 29, 2017

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

This comment has been minimized.

Copy link

laszbalo commented Jul 5, 2017

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

@jlyman

This comment has been minimized.

Copy link

jlyman commented Jul 6, 2017

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

@doudounannan

This comment has been minimized.

Copy link

doudounannan commented Jul 29, 2017

@jlyman which solution in docs?

@jlyman

This comment has been minimized.

Copy link

jlyman commented Jul 29, 2017

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

@thinkOfaNumber

This comment has been minimized.

Copy link

thinkOfaNumber commented Sep 6, 2017

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 #2550 (comment) since nothing else in #770 or here seemed to help...

@rochapablo

This comment has been minimized.

Copy link

rochapablo commented Sep 22, 2017

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

This comment has been minimized.

Copy link

calcazar commented Sep 27, 2017

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"

@thinkOfaNumber

This comment has been minimized.

Copy link

thinkOfaNumber commented Sep 27, 2017

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

@calcazar

This comment has been minimized.

Copy link

calcazar commented Sep 28, 2017

@thinkOfaNumber

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

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

@taras

This comment has been minimized.

Copy link

taras commented Sep 29, 2017

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

stuart-bennett added a commit to stuart-bennett/react-mixtape that referenced this issue May 19, 2018

Add Jest reference
Add a .babelrc with module options for test ENV because without this
Jest complains about import synax. (facebook/jest#2081)
@kasvtv

This comment has been minimized.

Copy link

kasvtv commented Jun 4, 2018

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.

@willb335

This comment has been minimized.

Copy link

willb335 commented Jun 12, 2018

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

@kasvtv

This comment has been minimized.

Copy link

kasvtv commented Jun 12, 2018

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 babel-core@7.0.0-bridge.0 for Jest to use version 7 of Babel.

@jeff1evesque

This comment has been minimized.

Copy link

jeff1evesque commented Jun 12, 2018

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?

@haywirez

This comment has been minimized.

Copy link

haywirez commented Jun 26, 2018

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'],

@macrozone

This comment has been minimized.

Copy link

macrozone commented Jul 2, 2018

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.

@macrozone macrozone referenced this issue Jul 2, 2018

Closed

Can't run jest tests with 0.56.0 #19859

3 of 3 tasks complete
@AndrewSouthpaw

This comment has been minimized.

Copy link

AndrewSouthpaw commented Jul 27, 2018

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.

@ryansully

This comment has been minimized.

Copy link

ryansully commented Jul 29, 2018

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

package.json

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

This comment has been minimized.

Copy link

duckscofield commented Jul 30, 2018

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

@joaquin-gimenez

This comment has been minimized.

Copy link

joaquin-gimenez commented Aug 7, 2018

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

@negarineh

This comment has been minimized.

Copy link

negarineh commented Aug 26, 2018

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

@schumannd

This comment has been minimized.

Copy link

schumannd commented Aug 28, 2018

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

@negarineh

This comment has been minimized.

Copy link

negarineh commented Aug 29, 2018

@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

@yih-en

This comment has been minimized.

Copy link

yih-en commented Sep 25, 2018

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

@jacksonkr

This comment has been minimized.

Copy link

jacksonkr commented Nov 22, 2018

This will only help SOME people.

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

@coryb08

This comment has been minimized.

Copy link

coryb08 commented Dec 28, 2018

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

@KrishnaPG

This comment has been minimized.

Copy link

KrishnaPG commented Jan 13, 2019

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.

@Dobby89

This comment has been minimized.

Copy link

Dobby89 commented Feb 15, 2019

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

@kasvtv

This comment has been minimized.

Copy link

kasvtv commented Feb 15, 2019

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment