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

@cypress/code-coverage报错:Unexpected token (win?.__coverage__)求助

解决@cypress/code-coverage的Module parse failed错误

问题背景

已完成以下配置:

  • 安装@cypress/code-coverage@^3.12.39
  • 在ui/e2e/cypress/support/e2e.js中添加:import "@cypress/code-coverage/support"
  • 在ui/e2e/cypress.config.js的setupNodeEvents方法中添加:require("@cypress/code-coverage/task")(on, config)

运行Cypress点击测试文件时触发如下错误:

./node_modules/@cypress/code-coverage/support.js 70:44
Module parse failed: Unexpected token (70:44)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     const saveCoverageObject = (win) => {
|       // if application code has been instrumented, the app iframe "window" has an object
>       const applicationSourceCoverage = win?.__coverage__
|       if (!applicationSourceCoverage) {
|         return
 @ ./cypress/support/e2e.js 55:0-40
 @ multi ./cypress/support/e2e.js

错误原因

错误行的win?.__coverage__使用了ES2020可选链操作符,当前项目的Webpack版本(大概率为4.x及以下)不原生支持该语法,且未配置Babel等转译工具处理node_modules中的@cypress/code-coverage包,导致Webpack无法解析该语法。

解决方案

方案1:升级Webpack到5.x版本

Webpack 5原生支持ES2020及以上语法特性,无需额外配置即可解析可选链操作符。执行以下命令升级:

npm install webpack@latest --save-dev
# 或使用yarn
yarn add webpack@latest --dev

方案2:配置Babel转译@cypress/code-coverage包

若无法升级Webpack,可修改Babel配置,将@cypress/code-coverage加入转译范围:

  1. 修改项目根目录的babel.config.js:
module.exports = {
  presets: [/* 你的现有preset配置 */],
  include: [
    /src/, // 原有业务代码路径
    /node_modules\/@cypress\/code-coverage/ // 添加该行转译目标包
  ]
}
  1. 若直接配置Webpack,确保babel-loader的include包含目标路径:
const path = require('path');

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [
          path.resolve(__dirname, 'src'),
          path.resolve(__dirname, 'node_modules/@cypress/code-coverage')
        ]
      }
    ]
  }
}

方案3:降级@cypress/code-coverage到兼容版本

如果上述方案均不可行,可降级到不使用可选链操作符的旧版本,比如3.10.0:

npm install @cypress/code-coverage@3.10.0 --save-dev
# 或使用yarn
yarn add @cypress/code-coverage@3.10.0 --dev

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:32:08