【问题标题】:"SyntaxError: Unexpected token export" using Jest with babel 7+“SyntaxError: Unexpected token export” 使用 Jest 和 babel 7+
【发布时间】:2019-01-16 01:12:03
【问题描述】:

我正在尝试通过测试覆盖基本的减速器,但它会在我的常量文件中引发导出错误:

 FAIL  jest/spec/reducers/RootReducer.spec.js
  ● Test 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)

我正在从 'project-root\tests' 文件夹运行测试

我要测试的 js 文件位于 'project-root\js' 文件夹中

我相信这是该错误的原因。因为我尝试导入的文件位于 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 或开玩笑配置中缺少的东西。但我找不到我的情况有什么问题,非常感谢任何提示我可以尝试什么

up: 有人建议我需要将 babel-jest 添加到我的 package.json 但它已经在 /node_modules - 它是用 jest 包

【问题讨论】:

    标签: ecmascript-6 jestjs babeljs


    【解决方案1】:

    问题在于您没有设置 babel-loader,因此项目将在编译期间未从源代码中删除的导入和导出命令上崩溃,因为 babel 不知道如何在没有 babel 的情况下处理它-装载机安装和配置。

    有关如何开始使用 ES6 转译和模块加载的快速示例,您可以查看此示例。

    youtube.com/watch?v=X5wTsHRsbIA

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 2018-08-22
      • 1970-01-01
      • 2019-11-10
      • 2016-02-12
      • 2016-09-30
      相关资源
      最近更新 更多