Jest: ES6 模块的意外令牌导入

创建于 2016-11-11  ·  93评论  ·  资料来源: facebook/jest

您要请求功能还是报告错误
报告错误

目前的行为是什么?
我现在在几个项目中使用相同的测试设置,全部来自我的样板。 最近所有这些都出现了这个问题,但我还没有找到它。 似乎 Jest 在我的 package.json 中缺少 babel 配置,并且测试套件因“意外令牌导入”而失败。 请记住,直到一周前,这个配置在几个项目中都成功运行,所以我假设它是一个回归并认为我应该报告它。

请注意,当我添加一个 .babelrc 文件时,测试套件通过了除一个测试之外的所有测试,在那里我得到了相同的 Unexpected Token Import,考虑到有十几个通过测试都使用 ES6 导入,这似乎很奇怪。 如果没有 .babelrc,所有 14 个测试都失败了。

如果当前的行为是一个错误,请提供重现的步骤,如果可能的话,我们可以在 GitHub 上提供一个最小的存储库,我们可以npm installnpm test

可以通过安装npm run setup并运行npm run test从我的样板中复制它。

什么是预期行为?
我希望以前有效的 Jest 配置仍然有效。 看起来我的预处理器不再像以前那样使用 babel-jest 运行了。

使用--debug再次运行 Jest 并提供它打印的完整配置。

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

最有用的评论

您可能都遇到了这个问题,因为 Node 不支持 ES 模块,并且您在将它们传送到浏览器时故意停止使用构建管道(webpack、rollup)编译它们。

您需要为 babelrc 中的“测试”环境启用从 ES 模块到 CommonJS 的编译,请参阅https://babeljs.io/docs/usage/babelrc/#env -option 和https://babeljs.io/docs/插件/转换-es2015-modules-commonjs/

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

所有93条评论

我对 React-Native 和 Jest 也有同样的问题,
如果您开始一个新项目:
react-native init AwesomeProject
cd 很棒的项目

然后安装一个模块,如 npm install native-base --save
将任何组件从 native-base 导入到 index.ios.js 文件中

npm test 会抛出这个错误:
../test/node_modules/native-base/index.js:4
从'./Components/vendor/react-native-drawer'导入抽屉;
^^^^^^
语法错误:意外的令牌导入

我遇到了同样的问题, @cpojer提供的链接似乎没有帮助😕

你好! 'transformIgnorePatterns' 确实......嗯......它必须这样做 - 忽略)
但是我如何才能在 node_modules 的包中使用该导入?

这个道具帮助了我:)

{
  "jest": {
    "verbose": true,
    "moduleDirectories": ["node_modules", "src"]
  },
}

UPD1
目前,我的 Jest 配置是:

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

...它对我有用:)

最好的问候,帕维尔·特列季亚科夫

大家好,我仍然遇到这个问题,但我没有使用 React Native。 问题总是使用 jest --no-cache 解决。 有没有办法让 jest 使用缓存工作,而不会抛出这个错误?

我无法将此转换与我的 create-react-app 应用程序一起使用。 在包含 ES6 导入的任何测试文件上始终获得“意外的令牌导入”。 我已经尝试了我能找到的所有建议。 no-cache 没有影响。 我显然不能从转换中忽略这些文件(它们需要被转换!)。

我放弃。 很高兴提供任何所需的信息。

我似乎也遇到了这个问题。

同样在这里

同样在这里

您可能都遇到了这个问题,因为 Node 不支持 ES 模块,并且您在将它们传送到浏览器时故意停止使用构建管道(webpack、rollup)编译它们。

您需要为 babelrc 中的“测试”环境启用从 ES 模块到 CommonJS 的编译,请参阅https://babeljs.io/docs/usage/babelrc/#env -option 和https://babeljs.io/docs/插件/转换-es2015-modules-commonjs/

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

谢谢你的回复,cpojer。 昨天我删除了我的节点 env 设置并让它以默认节点 env 运行,因为 jest 是全局工作的,但不是在使用节点脚本时。 它似乎解决了这个问题,所以我相信我的问题出在 node-env 设置上。 但它仍然是需要监控的。

编辑:这根本不起作用。 @cpojer的修复就像一个魅力。 谢谢。

@cpojer的修复对我

太棒了,也对我有用,谢谢!

我在我相当简单的 React Native 应用程序中遇到了类似的问题。

当运行npm testjest ,返回'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"
  }
}

@cpojer建议的 env 片段是否在 .package.json 中?
对不起,如果它真的很明显!
任何帮助都会很棒,谢谢

@JessicaBarclay它应该在你的 .babelrc 配置中。 像这样:

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

啊谢谢@rlage ! 排序:)

FWIW,我实际上在@cpojer建议的测试环境下使用正确的presetsplugins .babelrc设置了我的NODE_ENV=test在我的脚本行package.json

之前,因“意外的令牌导入”而失败:

"scripts": {
  ...
  "test": "jest",
}

之后,成功转换文件:

"scripts": {
  ...
  "test": "NODE_ENV=test jest",
}

@jlyman

基于 Jest 文档,它不应该被需要,因为 Jest 将 NODE_ENV 设置为默认测试。

注意:如果您使用更复杂的 Babel 配置,使用 Babel 的 env 选项,请记住 Jest 会自动将 NODE_ENV 定义为测试。 当没有设置 NODE_ENV 时,它不会像 Babel 那样默认使用 development 部分。

这个 .babelrc 对我有用:

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

注意:看起来很奇怪,但开发测试密钥都必须存在,否则将无法工作。

然后我就打电话:

node_modules/.bin/jest

或使用 package.json:

{"scripts": {"test": "jest"}}

无需设置 NODE_ENV 进行测试。

@laszbalo有趣的是,第二个env存在似乎确实可以解决问题。 如果我在开发环境中添加并在我的脚本中去掉显式的NODE_ENV前缀,它就可以工作。 我也读过那部分文档,但最终得到了那个解决方案,因为它有效。

@jlyman文档中的哪个解决方案?

@doudounannan对不起,如果不清楚。 我最终采用的解决方案是我在此处发布的内容。 就像@laszbalo所说的那样,这与使用 Babel 下文档所说的背道而驰,但是NODE_ENV test似乎都有效。

奇怪的是,当我使用"transformIgnorePatterns": [ ] babel 会转换我测试过的文件,但是如果我排除了transformIgnorePatterns选项,那么 babel 不会做任何事情......我有一个简单的 .babelrc 仅用于测试(我使用 webpack 进行生产,但不用于 jest 的测试):

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

我从https://github.com/facebook/jest/issues/2550#issuecomment -290812720 得到了这个想法,因为 #770 或这里似乎没有其他帮助......

不管我做什么,它总是相同的错误:

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

我有同样的问题。 我在我的笑话中添加了以下内容

"jest": {
     "preset": "react-native",
     "transformIgnorePatterns": [
          "node_modules/(?!react-native|react-navigation)/"
      ]
  }

现在运行 Jest 时出现以下错误:

ReferenceError:在“/Users/caalcaz/Documents/Projects/Enterprise-app/node_modules/enzyme/.babelrc”中指定的未知插件“transform-replace-object-assign”为0,尝试相对于“/Users/caalcaz/”进行解析文档/项目/企业应用程序/node_modules/酶”

@calcazar你的 node_modules/enzyme/.babelrc 中有什么?

我通过使用 babel-jest _and_ ts-jest 解决了它。 在 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
},

然后在 .babelrc (我只用于测试)

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

希望对某人有所帮助! (这是一个 aurelia 应用程序所以 YMMV)

@thinkOfaNumber

这就是我所看到的。 作为仅供参考,我正在运行 Enzyme V3.0

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

@thinkOfaNumber感谢您发布您的建议。 我用它来弄清楚如何从外部库中获取 es6 模块以在 jest 中进行编译。 关键在这里

"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

这是我需要它的部分。 非常感谢!

@rochapablo在同一个地方。 运气好的话?

Noop,现在我忽略了抛出错误的特定文件测试

下列的。 我有同样的问题,到目前为止似乎没有解决它。

也在关注

@rochapablo您是否已成功解决此问题?
由于您提到的问题,我也无法测试具有GiftedChat作为孩子的组件...

@todorone ,尝试添加:

"transformIgnorePatterns": [
      "node_modules/(?!react-native-gifted-chat)/"
]

@rochapablo感谢您的提示,但不幸的是它没有帮助。 我什至尝试进一步使用transformIgnorePatterns表达式,但没有帮助。

"transform": { "^.+\\.js$": "babel-jest", "^.+\\.jsx?$": "babel-jest" },
将以上内容添加到笑话中

@rochapablo您是否尝试过jest-expo预设? 运气好的话? 我遇到了另一个语法问题 & transformIgnorePatterns

仍然对我不起作用。 我得到该死的导入错误。
image

@testacode是一个动态的import ,你添加了必要的 babel 插件吗? 请参阅https://facebook.github.io/jest/docs/en/webpack.html#using -with-webpack-2 的底部

@SimenB谢谢,这就是我所缺少的!

这真有趣。 最近的一些更新删除了 babel-jest 的自动添加。 所以运行:

npm install babel-jest --save-dev

并在配置中添加 NOTHING ELSE 为我解决了这个问题。 我认为在错误消息中应该更清楚它不再包含...

我只是通过安装 babel-jest 解决了:
npm i babel-jest

另外,不要忘记创建一个包含以下内容的.babelrc文件:

{
    "presets": ["env", "react"]
}

这对我有用:

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

@hqro对我有用,谢谢👍

对我来说,我的.babelrc文件中有这个:

{
  "presets": ["react", ["env", { "modules": false }]],
  "plugins": [ ... ]
}

我只需要确保“测试”环境使用模块代替:

{
  "presets": ["react", ["env", { "modules": false }]],
  "plugins": [ ... ],
  "env": {
    "test": {
      "presets": ["react", "env"],
    }
  }
}

@nemoDreamer最好不要在一个配置中重复插件和预设

{
  "presets": ["react", ["env", { "modules": false }]],
  "plugins": [ ... ],
  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"],
    }
  }
}

无论我尝试什么,我都会出错。

> cross-env NODE_ENV=test jest --no-cache

 FAIL  src\views\Pay\__tests__\Pay.test.js
  ● Test suite failed to run

    C:\Users\***\Documents\Project\***\node_modules\ne-rc\lib\index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _Alert from './Alert';
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      11 |  * <strong i="6">@param</strong> {Array<Object>} [data] 每一种分期的详细信息 data=[{},{}...]
      12 |  * <strong i="7">@param</strong> {Number} [defaultSelected] 默认选中的下标
    > 13 |  * <strong i="8">@param</strong> {Funtion} [onClick] 点击触发事件
      14 |  * <strong i="9">@param</strong> {Number} [columnNum] 一行有多少列
      15 |  *
      16 |  * <strong i="10">@example</strong>

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
      at Object.<anonymous> (src/components/Installment/Installment.jsx:13:13)
      at Object.<anonymous> (src/components/Installment/index.js:8:20)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.693s

这是我的配置文件。

* .babelrc *

{
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ],
    // webpack understands the native import syntax, and uses it for tree shaking

    "es2015",
    "stage-2",
    // Specifies what level of language features to doPay.

    // Stage 2 is "draft", 4 is finished, 0 is strawman.

    // See https://tc39.github.io/process-document/

    "react"
    // Transpile React components to JavaScript
  ],
  "env": {
    "test": {
      "presets": ["env", "react", "stage-2"],
      "plugins": [
        "transform-es2015-modules-commonjs"
      ]
    }
  }
}

包.json

{
  "main": "index.js",
  "scripts": {
    "dev": "cross-env NODE_ENV=development node ./server/server.js",
    "api": "cross-env NODE_ENV=api node ./server/server.js",
    "clean": "rm -rf dist",
    "dist": "npm run clean && cross-env NODE_ENV=production webpack --config ./webpack/index.js --progress --colors",
    "online": "cross-env NODE_ENV=development node ./server/online.js",
    "lint": "node ./node_modules/eslint/bin/eslint.js ./src --fix",
    "test": "cross-env NODE_ENV=test jest --no-cache",
    "test:watch": "npm test --watch",
    "stats": "npm run clean && cross-env NODE_ENV=production webpack --config ./webpack/index.js --profile --json > stats.json",
    "gatest": "node ./service/gatest.js"
  },
  "pre-commit": [
    "lint"
  ],
  "jest": {
    "verbose": true,
    "modulePaths": [
      "<rootDir>/src",
      "<rootDir>/node_modules"
    ],
    "setupFiles": [
      "./test/setup.js"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "md"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
    ],
    "transform": {
      "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "testEnvironment": "jsdom"
  },
  "devDependencies": {
    "asset-inject-html-webpack-plugin": "^0.9.1",
    "autoprefixer": "^7.1.3",
    "babel": "^6.23.0",
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.2.1",
    "babel-jest": "^22.4.1",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-jest": "^22.4.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "babel-register": "^6.26.0",
    "better-npm-run": "0.1.0",
    "body-parser": "^1.17.2",
    "chalk": "^2.1.0",
    "cross-env": "^5.0.5",
    "css-loader": "^0.28.5",
    "deepmerge": "^2.0.1",
    "enzyme": "^3.3.0",
    "eslint": "^4.5.0",
    "eslint-config-standard": "^11.0.0-beta.0",
    "eslint-config-standard-jsx": "^4.0.2",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-node": "^5.1.1",
    "eslint-plugin-promise": "^3.5.0",
    "eslint-plugin-react": "^7.3.0",
    "eslint-plugin-standard": "^3.0.1",
    "exports-loader": "^0.6.4",
    "express": "^4.15.4",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^1.1.6",
    "git-repo-info": "^1.4.1",
    "glob": "^7.1.2",
    "happypack": "^4.0.1",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "idb": "^2.0.4",
    "imports-loader": "^0.7.0",
    "jest": "^22.4.2",
    "lodash.range": "^3.2.0",
    "mocha": "^5.0.0",
    "node-sass": "^4.5.3",
    "node-xlsx": "^0.11.2",
    "postcss-loader": "^2.0.6",
    "pre-commit": "^1.2.2",
    "react-hot-loader": "^3.0.0-beta.6",
    "react-test-renderer": "^16.2.0",
    "redux-logger": "^3.0.6",
    "regenerator-runtime": "^0.11.1",
    "request": "^2.74.0",
    "require-reload": "^0.2.2",
    "rimraf": "^2.6.0",
    "sass-loader": "^6.0.6",
    "script-loader": "^0.7.0",
    "sinon": "^4.2.0",
    "style-loader": "^0.19.1",
    "uglify-js": "^3.0.28",
    "url-loader": "^0.6.2",
    "webpack": "^3.5.5",
    "webpack-bundle-analyzer": "^2.9.0",
    "webpack-dev-middleware": "^2.0.4",
    "webpack-dev-server": "^2.7.1",
    "webpack-hot-middleware": "^2.18.2",
    "webpack-merge": "^4.1.0",
    "worker-loader": "^1.1.0"
  }
}

.babelrc设置预设时,请确保"env"位于方括号["env"] ,如下所示:

  "env": {
    "test": {
      "presets": [["env"], "stage-2"],
      "plugins": ["transform-es2015-modules-commonjs", "dynamic-import-node"]
    }
  }

特别是如果您的配置中有"modules: false"

此外,默认情况下, jest 不会转换node_modules ,参见https://facebook.github.io/jest/docs/en/configuration.html#transformignorepatterns -array-string

这就是为什么任何import ...node_modules文件中都不起作用的原因。 要禁用此功能,您可以添加:

transformIgnorePatterns: []

到你的笑话配置。

希望这可以帮助!

@florentchauveau谢谢,这对我

@todorone @rochapablo你们找到解决方案了吗? 即使我面临同样的问题-

    import * as React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
      at Object.<anonymous> (node_modules/@expo/react-native-action-sheet/index.js:1:107)

我只在使用组件的测试中收到此错误
GiftedChat - https://github.com/FaridSafi/react-native-gifted-chat。
也许这是因为@expo/react-native-action-sheet是作为 ES6 模块发布的,而GiftedChat正在内部使用它? 但是如果添加了预设, jest / ts-jest (我不确定)应该处理这个问题。 这是我的 Jest 配置 -

    "jest": {
        "preset": "react-native",
        "moduleFileExtensions": [
            "ts",
            "tsx",
            "js"
        ],
        "transform": {
            "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
            "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
        },
        "transformIgnorePatterns": [
            "node_modules/(?!rn-placeholder|react-native|react-navigation|native-base|react-native-datepicker|native-base-shoutem-theme|@shoutem/animation|@shoutem/ui|tcomb-form-native)"
        ],
        "setupTestFrameworkScriptFile": "<rootDir>/src/__mocks__/Adapter.js",
        "testRegex": "(\\.(test|spec))\\.(ts|tsx|js)$",
        "testPathIgnorePatterns": [
            "\\.snap$",
            "<rootDir>/node_modules/",
            "<rootDir>/lib/"
        ],
        "moduleNameMapper": {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.js"
        },
        "cacheDirectory": ".jest/cache"
    },

.babelrc -

{
    "presets": ["react-native"]
}

我已经尝试了几乎所有上面提到的解决方案。 他们都没有在我的场景中工作。 需要帮助。

@omkarjoshi-cc 在我工作时唯一对我有用的是添加引发错误的包,在我的情况下是:

"transformIgnorePatterns": [
      "node_modules/(?!react-native-gifted-chat)/"
]

@rochapablo是的。 我尝试过这个。 没用。 还有其他可能遗漏的东西吗? 这真的很令人沮丧😓

我正在使用 babel 7,我也仍然没有使用“transformIgnorePatterns” - 尝试了许多不同的正则表达式:/

我遇到的问题是一个依赖项中包含原生 es6 类,并且我的源中有一个扩展它的类。 由于 Babel 转译的“es5 类”无法扩展本机类,因此我在开玩笑时遇到运行时错误。

我开始认为“babel/preset-env”以某种方式妨碍了将代码转换为 jest(目标节点)的方式,它可能不遵循浏览器目标,但仍然不确定。

有谁知道在 .babelrc 中使用“present-env”时如何将所有内容强制为 es5 以开玩笑?

我能想到的唯一解决方法是不使用 babel-jest,运行 webpack(它使用 babel-loader,以及转换文件的规则对我有用),然后运行 ​​jest -> 我正在考虑使用webpack -w并开玩笑地观看转译的..)

添加

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

为我工作。 感谢@rochapablo 🙌

我正在努力解决这个问题。 我正在测试的输出文件夹应该是带有import等的 ES6 语法还是可以不测试? 我在输出文件/文件中没有看到任何 commonjs(与 react-native 一起使用)

我面临同样的问题,这个页面解决了这个问题:
https://babeljs.io/docs/plugins/transform-es2015-modules-commonjs/

出于某种原因,而不是babel-jest ,使用以下使其对我有用(显然尊重transformIgnorePatterns

"transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "ts-jest-babel-7"
    }

btw 这个问题应该在这里重新打开吧? 许多人面临困难

就我而言,事实证明这个问题是由于忽略了我的 babel 配置中的测试文件引起的。 由于不相关的原因,我的 .babelrc 中有"ignore": ["**/*.test.js"]

解决方案是只为生产环境设置忽略选项,即:

"env": {
    "production": {
      "ignore": [
        "**/*.test.js"
      ]
    }
  }

或者,您可以为测试环境指定一个特殊的忽略模式。

在尝试了很多之后,这是我的情况

  1. 确保拥有正确版本的 babe-jest *
  2. 确保具有预设的 .babelrc 配置(以前安装)
  3. 如果它仍然抛出“意外令牌”错误可能是未识别的箭头函数,则此 babel 插件将帮助您“转换类属性”还将它们包含在您的 babel 配置中。

这是我的配置。

.babelrc

{
  "plugins": [
    "transform-es2015-modules-commonjs",
    "transform-class-properties"
  ]}

对于酶(setupTests.js)

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-15";
configure({ adapter: new Adapter() });

包.json

 "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "eslint": "^4.19.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-test-renderer": "^15.6.2",
     "babel-jest": "^22.4.3",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-15": "^1.0.5",
    "gh-pages": "^0.12.0",
    "jest": "^22.4.3",
    "react-addons-test-utils": "^15.4.2",
    "regenerator-runtime": "^0.11.1"
  },
"jest": {
    "globals": {
      "NODE_ENV": "test"
    },
    "verbose": true,
    "moduleDirectories": ["node_modules", "src"],
    "transform": {
      "^.+\\.jsx?$": "babel-jest"
    },
    "moduleFileExtensions": ["js", "jsx"],
    "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js"
  }

yarn add --dev babel-jest babel-core regenerator-runtime添加这个对我有用

就我而言,这是 Windows 及其愚蠢权限的问题,可能没有正确设置 env 变量。
从 git bash 切换到提升的cmd.exe并重新开始工作。

我将jest定义为script (将test:jest重命名为test ),在我的package.json 。 但是,当运行npm run test ,我得到SyntaxError: Unexpected token import

root<strong i="14">@browserify</strong>:/var/machine-learning/src# npm run test

> [email protected] test /var/machine-learning/src
> jest --config /var/machine-learning/test/jest/jest.config.js

 FAIL  ../test/jest/__tests__/layout/analysis.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/layout/analysis.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/layout/page.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/layout/page.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/content/register.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/content/register.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/content/login.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/content/login.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |        0 |        0 |        0 |        0 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 4 failed, 4 total
Tests:       0 total
Snapshots:   0 total
Time:        3.782s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: `jest --config /var/machine-learning/test/jest/jest.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-05-08T01_50_42_754Z-debug.log

我还定义了一个对应的jest.config.js

module.exports = {
  'verbose': true,
  'collectCoverage': true,
  'coverageDirectory': '/var/machine-learning',
  'moduleDirectories': ['/var/machine-learning/src/node_modules'],
  'transformIgnorePatterns': [
    '/var/machine-learning/src/node_modules'
  ]
}

我看到很多关于react-nativetransformIgnorePatterns的事情。 幸运的是,不幸的是,我不使用它。 这是一个多么难以捉摸的错误。 我需要定义.babelrc ,还是在package.json添加jest指令。 如果是这种情况,我的笑话script怎么知道 babel 呢? 我试图在包含我的package.json的同一目录中添加一个.babelrc ,但没有运气:

{
  "env": {
    "test": {
      "presets": ["env", "stage-2", "react"]
    }
  }
}

注:如果有人想保持我原来的轨道问题有关上述问题。

经过大量的鬼混,我发现了以下问题:

  • Jest 默认运行 babel 6。 Babel 6 不会查找.babelrc.js文件。 仅适用于.babelrc文件。 如果你有一个 JS 配置而不是 JSON,它不会读取配置,因此不会使用任何插件。 这为我带来了unexpected token: import
  • babel-7-jest运行在旧的 Babel 7 核心引擎上,从而破坏了对新提案插件的支持。
  • 似乎npm i -D [email protected]完全解决了这个问题。 我的 babel 配置中甚至没有env.test ,也没有任何 jest 配置。

似乎 Jest 寻找babel-core (因此忽略@babel/core ),否则它会退回到 Babel 6 并跳过您的配置。 但是当安装了最新的 babel-core(桥接版本)时,它会解析 ES6 模块,而无需任何额外的配置。

感谢 kasvtv! 将我的.babelrc.js更改为.babelrc并安装npm i -D [email protected] 。 现在我的测试用babel-jest

您可以安全地使用 .js 配置文件。 只是 Babel 从第 7 版开始只能读取这种类型的文件,并且您需要[email protected] 才能让 Jest 使用 Babel 的第 7 版。

如果有人感兴趣,我的玩笑+酶测试开始工作了。 随意进入相应的配置文件。 另外,有没有人有兴趣帮助同一个项目的前端开发?

由于antdrc-calendar等库无法导入模块而出现类似问题,解决方案是配置transformIgnorePatterns

transformIgnorePatterns: [ 'node_modules/?!(antd|rc-.+)/' ],

也许moduleDirectories帮助:

moduleDirectories: ['node_modules'],

我更新到最新的 react-native 版本,不得不更新到 babel 7,现在我遇到了同样的错误。

将这些 node_modules 添加到transformIgnorePatterns中似乎不再做任何事情。

就我而言,这是因为我不再使用 Babel 转译模块,并且在入门指南中有一个注释,说明将其添加回 babelrc 的test部分。

@kasvtv @willb335我使用一个技巧让 Babel 6 识别 .babelrc.js:

包.json

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

我在使用@material/base 库时遇到了同样的问题,谁能提供package.json.babelrc文件来解决。 我尝试了上述反馈,但我混淆了......

我的解决方案是在 .babelrc 文件上添加“env”预设,结果是这样的
{
"预设": ["env", "es2016", "stage-0", "react"]
}

使用此链接信息解决了我的问题
https://jestjs.io/docs/en/webpack.html

@negarineh您的链接无效

使用@haywirez提供的transformIgnorePatterns解决方案将我的

SyntaxError: Unexpected token import

错误成

TypeError: Cannot read property 'DocumentDir' of undefined

错误。 即包 (rn-fetch-blob) 现在未定义。

编辑:

实际上只是将transformIgnorePatterns: [],到我的jest.config.js会导致 SyntaxError 更改为 TypeError。

@schmannd对不起,我犯了一个错误,该链接现在正在将您重定向到该页面。 如果您使用链接中提供的配置设置“jest.config.js”,它应该可以工作。
如果错误是关于导入 .css 文件,则添加一个模拟文件,如链接中的示例,或者仅通过使用此配置安装“identity-obj-proxy”应该可以工作:

npm install --save-dev identity-obj-proxy

jest.config.js(用于 CSS 模块):

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

另外,这是我在项目根目录下的 .babelrc 文件(test.config.js 也应该在根目录下):

首先,要使用 babel 安装“babel-jest”和“regenerator-runtime”:

npm --dev babel-jest babel-core regenerator-runtime

然后将此配置添加到 .babelrc 文件中:

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

希望这可以帮助。
https://jestjs.io/docs/en/webpack.html

就我而言,它在添加以下.babelrc

{
  "presets": ["env", "react"],
  "env": {
    "test": {
      "plugins": ["transform-class-properties"]
    }
  }
}

然后使用NODE_ENV=test jest运行测试

这只会帮助一些人。

我的问题是由于开玩笑无法解析我的 JS 文件。 我用require代替。

伙计们。 这些解决方案都不起作用,因为我没有 babelrc 文件……只有 babel.config.js。 请问,你如何用 babel.config.js 修复? 谢谢

从上面的讨论中尝试了许多关于babel配置的内容以及来自其他搜索的一些额外选项(例如esm选项) - 没有任何效果。 import 关键字继续从笑话中给出错误。 遗憾的是,使用 es6 导入测试模块是如此困难。

最后,这对我有用

现在,我没有在我的代码中使用任何打字稿,但仍然使用了ts-jest (因为打字稿内部支持导入和所有其他内容)。 这只是为了让玩笑正确理解 javascript 代码。

遵循了以下步骤:
npm i -D jest typescript ts-jest @types/jest
jest.config.js文件中:
transform: { "\\.js$": "ts-jest", transformIgnorePatterns: [], },
Jest 可能会抱怨 typescript 不允许js文件被编译。 使用以下选项添加tsconfig.json文件:
{ "compilerOptions": { "allowJs": true, "module": "commonjs", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "sourceMap": true } }
删除了所有与babel相关的配置和文件。 npm配置如下所示:
"scripts": { "test": "jest --runInBand --detectOpenHandles --no-cache --config ./jest.config.js" }
希望这可以帮助任何面临类似进口问题的人。

有没有人有一个使用 JS 导入的工作设置的裸机存储库?

有没有人有一个使用 JS 导入的工作设置的裸机存储库?

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

作为在搜索可能与原始讨论无关的类似问题时发现此页面的人。 我的问题最终是由于使用了https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports描述的类似函数的动态导入https://github.com/airbnb/babel-plugin-dynamic-import-node提供的此功能添加 babel 插件并相应地修改 .babelrc 来解决这个问题。

{
    ...
    "env": {
        "test": {
            "plugins": ["dynamic-import-node"]
        }
    ...
}

我只是删除了选项:{ module:false },然后它就可以工作了

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

transformIgnorePatterns: []到 jest 配置并将transform-es2015-modules-commonjs到 babelrc 为我解决了这个问题。
开玩笑:^23.1.0,
巴别塔:6.26.3

@ngmgit但这意味着您转译了所有 node_modules,这不是最佳选择...

就我而言,
.babelrc不起作用,但我通过将.babelrc相同设置移动到babel.config.js解决了问题。

希望有帮助!

这里的一切都对我不起作用。 我不敢相信 facebook 的官方测试库来测试 React 应用程序的配置难度如此之大,我是一名拥有 8 年以上经验的开发人员,我每天花了 5 个小时但没有成功解决这么多问题关于堆栈溢出。

我只是无法配置我的反应应用程序来使用 jest + react-testing-library

这只是因为开玩笑每次都向我大喊他无法处理的新语法错误。 我使用的每个插件都可以解决一个问题并提供另一个问题。 有没有办法让 babel 处理一切?

我真诚地完成了我真的放弃了,我不再花更多时间在这上面,我可能会取消在项目中添加这个库。

说真的,看到任何想要使用 jest + react-testing-library 测试 React 应用程序的人都没有默认配置是非常奇怪的。

经过数小时的反复试验和许多 SO 答案和 github 问题, @cpojer的答案对我

更新了最新和最好的一些额外的上下文,帮助了我:

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

依赖项:

当不在项目的根目录中运行 jest 时,也会发生此问题...

如果您使用react-nativejest-expo预设并且在您的项目中有.js文件,您应该在 jest 配置中设置transform以匹配它。
我使用了https://jestjs.io/docs/en/configuration.html#transform -objectstring-pathtotransformer--pathtotransformer-object 中的一个表达式并且它起作用了。

transform: { '^.+\\.[jt]sx?$': 'babel-jest' }

支持

我想在这里给 pnpm 用户留个便条....

以下示例不适用于 pnpm 用户,因为 pnpm 路径不同。 上述正则表达式仅适用于扁平化的node_modules目录。

/xxx/node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/antd/es/input/String

请参阅: https :

"transformIgnorePatterns": [
  "node_modules/(?!(react-native|my-project|react-native-button)/)"
]

https://jestjs.io/docs/en/tutorial-react-native#transformignorepatterns -customization

使固定

通过添加.*对最后一次出现使用负前瞻。

node_modules/(?!(.*antd/es)/)
此页面是否有帮助?
0 / 5 - 0 等级