首页 > 解决方案 > Jest SyntaxError:意外的令牌导出

问题描述

运行 npm test 时,我收到以下错误消息,我不知道什么以及如何解决。

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

 …\node_modules\@babel\runtime\helpers\esm\objectWithoutPropertiesLoose.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export default function _objectWithoutPropertiesLoose(source, excluded) {
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at Object.<anonymous> (node_modules/react-spring/renderprops.js:7:53)

这是我的 package.json

  "dependencies": {
"@material-ui/core": "^4.6.0",
"@material-ui/icons": "^4.5.1",
"@material-ui/styles": "^4.6.0",
"@material/react-card": "^0.15.0",
"axios": "^0.19.0",
"connected-react-router": "^6.5.2",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0",
"react-spring": "^8.0.27",
"redux": "^4.0.4",
"redux-devtools-extension": "^2.13.8",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0"
 },
   "scripts": {
    ......
},
 "proxy": "http://localhost:8082",
"eslintConfig": {
   "extends": "react-app"
 },
  "browserslist": {
"production": [
  ">0.2%",
  "not dead",
  "not op_mini all"
],
"development": [
  .....
]
 },
     "devDependencies": {
      "@testing-library/jest-dom": "^5.1.1",
        "@testing-library/react": "^10.0.1"

知道是什么问题吗?

谢谢

标签: reactjs

解决方案


https://jestjs.io/docs/en/configuration#transformignorepatterns-arraystring

这就是发生的事情This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

这是你需要做的:To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.

Jest 无法测试用 es6 编写的文件,因此您需要将导入的模块转换为纯 js,然后才能运行测试


推荐阅读