在使用Jest和Babel 7+时出现“SyntaxError:Unexpected token export”。

3

我试图用一个测试来覆盖基本的reducer,但它在我的常量文件中的导出处抛出错误:

 FAIL  jest/spec/reducers/RootReducer.spec.jsTest suite failed to run

    Jest encountered an unexpected token

    Details:

    project-root\js\src\constants\ActionTypes.js:2
    export const LOCALE_REQUEST = 'ROOT/LOCALE_REQUEST';
    ^^^^^^

    SyntaxError: Unexpected token export

      1 | 'use strict';
      2 |
    > 3 | import { LOCALE_REQUEST_SUCCESS, ROUTING_REQUEST_SUCCESS } from '/js/src/constants/ActionTypes';
        | ^
      4 |

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (jest/spec/reducers/RootReducer.spec.js:3:1)

我正在运行来自“项目根目录\tests”文件夹的测试。

我想要测试的js文件位于“项目根目录\js”文件夹中。

我相信这就是bug的原因。因为我尝试导入的文件在tests文件夹之外,所以它看起来没有被转译。

这是我的package.json

{
  "name": "jest",
  "version": "0.0.0",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/plugin-transform-modules-commonjs": "^7.2.0",
    "@babel/preset-env": "^7.2.3",
    "babel-core": "7.0.0-bridge.0",
    "jest": "^23.6.0"
  }
}

这是.babelrc文件:
{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"
  ]
}

这是jest.config.js文件:

module.exports = {
    verbose: true,
    transform: {
        "^.+\\.jsx?$": "babel-jest"
    },
    bail: true,
    browser: true,
    cacheDirectory: '/tmp/jest',
    collectCoverage: false,
    roots: [
        '<rootDir>/../js',
        '<rootDir>/jest'
    ],
    moduleNameMapper: {
        '^(.*)/js/(.*)$': '<rootDir>/../js/$2'
    },
    testRegex: '(jest/spec/.*|(\\.|/)(test|spec))\\.js$',
    testPathIgnorePatterns: [
        '<rootDir>/node_modules'
    ],
    transformIgnorePatterns: [
        '/node_modules/'
    ]
};

所以我试图在网上寻找类似的案例,但在大多数情况下,问题来自于/node_modules或jest配置中缺少某些内容。但是在我的情况下,我找不到问题出在哪里,非常感谢任何提示我可以尝试的内容。

更新:有人建议我需要将babel-jest添加到我的package.json中,但它已经存在于/node_modules中-它是与jest包一起添加的。

1个回答

0
问题在于您没有设置babel-loader,因此在导入和导出命令未在编译期间从源代码中删除时,项目将崩溃,因为babel不知道如何处理没有安装和配置babel-loader的情况。
如果您想快速了解如何开始使用ES6转码和模块加载,请查看此示例。

youtube.com/watch?v=X5wTsHRsbIA


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