Skip to content
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 · 97 comments
Closed

Unexpected Token Import for ES6 modules #2081

RyanCCollins opened this issue Nov 11, 2016 · 97 comments

Comments

@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
Copy link

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
Copy link
Member

cpojer commented Nov 14, 2016

See http://facebook.github.io/jest/docs/tutorial-react-native.html#transformignorepatterns-customization

@cpojer cpojer closed this as completed Nov 14, 2016
@fuyi
Copy link

fuyi commented Feb 4, 2017

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

@DmitrySkripunov
Copy link

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

@paveltretyakovru
Copy link

paveltretyakovru 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
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
Copy link

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
Copy link

joshjung commented Jun 1, 2017

I seem to also be experiencing this issue.

@miketeix
Copy link

miketeix commented Jun 5, 2017

Same here

1 similar comment
@dangreenisrael
Copy link

Same here

@cpojer
Copy link
Member

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

@heyjordn
Copy link

heyjordn commented Jun 17, 2017

@cpojer 's fix worked for me, thanks

@nighto
Copy link

nighto commented Jun 21, 2017

Awesome, also worked for me, thanks!

@JessicaBarclay
Copy link

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
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
Copy link

Ahh Thank you @rlage ! Sorted :)

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

@negativeentropy9
Copy link

@jlyman which solution in docs?

@jlyman
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
Copy link

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
Copy link

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
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
Copy link

@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
Copy link

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

@JacobMonono
Copy link

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

@zhanzizhen
Copy link

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

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

@ngmgit
Copy link

ngmgit commented Dec 12, 2019

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

@kirill-konshin
Copy link

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

@ho1234c
Copy link

ho1234c commented Jan 10, 2020

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

hope it helped!

@itspauloroberto
Copy link

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.

@loganpowell
Copy link

loganpowell commented Apr 25, 2020

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:

@valley-of-dev
Copy link

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

@Roman-Mzh
Copy link

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

@vjpr
Copy link

vjpr commented Sep 26, 2020

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

@joshuarobs
Copy link

joshuarobs commented Dec 9, 2020

Shame that even after all these years this is still an issue. CRA + Jest works fine with Typescript, with 0 config, until it doesn't. Everything goes well doing basic work, until you need to import another Typescript library, then your compiler will start to complain and your Jest tests won't work, because its not smart enough to understand Typescript. And then when you google all these solutions/workarounds on stackoverflow, on github, etc. none of these actually do anything.

I just wish there was an in-built way for Jest to work with typescript imported modules. Setting transformIgnorePatterns in the jest.config.js doesn't do anything. Setting that in the npm script via "test": "react-scripts test --transformIgnorePatterns \\\"node_modules/(?!@joshuarobs/clothing-enums)/\\\"\"", doesn't do anything. None of these workarounds work, for a simple newly made CRA.

@loganpowell
That solution doesn't work for me unfortunately. Do you have a clean repo that replicates this?

@IlyaZha
Copy link

IlyaZha commented Dec 10, 2020

This code helped me:

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

where "test" - your enviroment

@yotam-frid
Copy link

been wracking my head over this for many hours now, literally NOTHING in this thread works. why is the solution so inconsistent??? this shouldn't be such a hard problem to solve but i've wasted almost an entire day of work on this, and still nothing works. can't believe this issue has been open for 5 years.

@SimenB
Copy link
Member

SimenB commented Jan 4, 2021

can't believe this issue has been open for 5 years.

It was closed 3 days after it was opened, 4 years ago

image

Please see https://jestjs.io/docs/en/ecmascript-modules

@jestjs jestjs locked as resolved and limited conversation to collaborators Jan 4, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests