Babel 7和Jest:意外的标记导出

5

我在使用Babel7运行jest测试时遇到了问题,这些测试在Babel6下能够很好地转译。虽然它可以通过Webpack和Babel7完美编译,但是由于转译错误而无法在Jest中运行测试。我做错了什么?

react/node_modules/generic-redux-root/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './source/CreateReduxRoot';
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

我的Jest配置
{
"unmockedModulePathPatterns": [
  "<rootDir>/node_modules/react",
  "<rootDir>/node_modules/react-dom",
  "<rootDir>/node_modules/react-addons-test-utils",
  "<rootDir>/node_modules/fbjs",
  "enzyme"
],
"roots": [
  "<rootDir>/__tests__"
],
"transformIgnorePatterns": [
  "node_modules/(^generic-)/i", //a module matching this is throwing an error
  "node_modules/react-infinite-scroller"
],
"setupFiles": [
  "./jestsetup.js"
],
"snapshotSerializers": [
  "enzyme-to-json/serializer"
],
"testResultsProcessor": "./jestTrxProcessor",
"verbose": true

我的.babelrc文件

{
"presets": [
    [
        "@babel/preset-env",
        {
            "targets": {
                "ie": 11
            },
            "useBuiltIns": "usage"
        }
    ],
    "@babel/preset-react"
],
"plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-syntax-dynamic-import",
    "@babel/plugin-syntax-import-meta",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-json-strings",
    [
        "@babel/plugin-proposal-decorators",
        {
            "legacy": true
        }
    ],
    "@babel/plugin-proposal-function-sent",
    "@babel/plugin-proposal-export-namespace-from",
    "@babel/plugin-proposal-numeric-separator",
    "@babel/plugin-proposal-throw-expressions",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-transform-object-assign"
]

我做错了什么?

该怎么办呢?


也许对于那些在Babel 7和Jest上遇到问题的人来说,这篇React测试教程可能会很有用。 - Robin Wieruch
1个回答

19
这是因为Babel 7不再自动加载你的.babelrc文件。现在有一个新的概念叫做root config,它应该位于项目的根目录下,并且文件名必须被命名为babel.config.js并导出一个对象。
所以,这里给你一些要遵循的步骤:
  1. .babelrc重命名为babel.config.js,并确保使用module.exports = {...}
  2. 运行jest --clearCache来清除Jest内部缓存(这花费了我几个小时的时间)
  3. 此时你的babel配置应该已经被Jest正确加载了

谢谢你的帮助!那似乎解决了这个错误,但现在我面临另一个奇怪的错误。我已经为此创建了一个问题https://stackoverflow.com/q/52400840/1032179 - Salman Hasrat Khan
太棒了! :) 在找到这个答案之前,我已经苦思冥想了几个小时 :) - kovpack
1
请确保您没有设置modules: false;) - Tomas Ramirez Sarduy
哇,modules: false 完全为我们完成了它。 - Frexuz
我花了一整天的时间解决这个问题。 对我来说,从 .babelrcbabel.config.js 是可行的。 谢谢,伙计。 - LogicalAnt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接