You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue项目运行Jest测试报Unexpected token 'export'错误如何解决?

问题解决方案

问题根源

报错中的_asyncToGenerator是Babel转译async/await语法时自动生成的辅助函数,出现Unexpected token 'export'错误是因为Babel转译输出了ES模块规范的export语法,但Jest默认采用CommonJS规范加载代码,无法识别ES模块导出语句。

修复步骤

  • 第一步:修正Babel配置文件命名
    你当前的配置文件名为babel.config.jss,多了末尾的s,请重命名为正确的babel.config.js,否则Babel无法读取配置,会使用默认规则转译代码。
  • 第二步:调整Babel配置,强制测试环境输出CommonJS模块
    修改babel.config.js内容如下,解决@vue/app预设与@babel/preset-env的配置冲突,测试环境下强制转译为CommonJS规范:
module.exports = {
  presets: [
    ['@vue/app', {
      modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false
    }]
  ],
  plugins: [
    '@babel/plugin-proposal-nullish-coalescing-operator',
    '@babel/plugin-proposal-optional-chaining',
    '@babel/plugin-proposal-logical-assignment-operators',
    '@babel/plugin-proposal-numeric-separator',
  ],
};
  • 第三步:修改Jest配置,增加ES模块转译规则
    在jest.config.json中添加transformIgnorePatterns配置,允许转译node_modules中用到的ES模块依赖:
{
  "verbose": true,
  "testEnvironment": "node",
  "moduleFileExtensions": ["js", "vue"],
  "moduleNameMapper": {
    "^@/(.*)$": "<rootDir>/resources/assets/js/components/$1"
  },
  "transform": {
    "^.+\\.js$": "babel-jest",
    ".*\\.(vue)$": "vue-jest"
  },
  "transformIgnorePatterns": [
    "node_modules/(?!(.*\\.mjs$|@babel/runtime))"
  ],
  "snapshotSerializers": ["jest-serializer-vue"]
}
  • 第四步:配置测试环境变量
    因为你使用Windows系统,默认不会自动设置NODE_ENV,请先安装cross-env:
yarn add cross-env -D

然后修改package.json中的test脚本:

{
  "scripts": {
    "test": "cross-env NODE_ENV=test jest"
  }
}
  • 第五步:验证版本一致性
    确认babel-jest的大版本与你安装的Jest版本(27.x)保持一致,如果版本不匹配请执行:
yarn add babel-jest@27 -D

完成以上步骤后重新执行yarn test即可正常运行测试用例。

内容的提问来源于stack exchange,提问作者eunhee ju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:51:01