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

GitLab流水线中Cypress E2E测试覆盖率报告生成失败排查

解决GitLab流水线中Cypress E2E覆盖率报告生成失败的问题

核心排查与修复步骤

1. 强制CI环境下的代码插桩生效

本地能看到window.__coverage__但流水线无数据,大概率是插桩插件在CI环境未启用。修改vite.config.ts,强制开启插桩逻辑:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import istanbul from 'vite-plugin-istanbul';

export default defineConfig({
  plugins: [
    react(),
    istanbul({
      enforce: 'post',
      include: 'src/*',
      exclude: ['node_modules', 'test/', 'src/**/*.spec.tsx'],
      extension: ['.js', '.jsx', '.ts', '.tsx'],
      requireEnv: false, // 关闭环境变量校验,强制生成覆盖率数据
    }),
  ],
  build: {
    sourcemap: process.env.CI ? true : false, // CI环境生成sourcemap,保证覆盖率路径匹配
  },
});

2. 确保Cypress覆盖率插件正确加载

在cypress.config.ts中明确注册覆盖率任务,避免CI环境下插件失效:

import { defineConfig } from 'cypress';
import codeCoverage from '@cypress/code-coverage/task';

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      codeCoverage(on, config);
      return config;
    },
  },
  video: !process.env.CI, // CI环境禁用视频,减少资源占用
});

同时在cypress/support/e2e.ts(或.js)中导入支持文件:

import '@cypress/code-coverage/support';

3. 修正GitLab流水线的执行逻辑

调整.gitlab-ci.yml,确保服务启动顺序、环境变量和命令执行正确:

stages:
  - install
  - test
  - sonar

install_deps:
  stage: install
  script:
    - npm install
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/

run_e2e_tests:
  stage: test
  script:
    # 后台启动Vite服务,等待就绪后再执行测试
    - npm run dev &
    - npx wait-on http://localhost:5173
    # 强制启用覆盖率收集,运行Cypress测试
    - npx cypress run --env coverage=true
    # 手动触发nyc生成报告(兜底自动生成失败的情况)
    - npx nyc report --reporter=lcov --reporter=json
  artifacts:
    paths:
      - .nyc_output/
      - coverage/
    expire_in: 1 week

sonar_scan:
  stage: sonar
  script:
    # 替换为你的SonarQube扫描参数,确保指向正确的覆盖率报告路径
    - npx sonar-scanner -Dsonar.projectKey=你的项目Key -Dsonar.sources=src -Dsonar.test.inclusions=**/*.spec.tsx -Dsonar.javascript.coveragePlugin=lcov -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info -Dsonar.host.url=你的Sonar地址 -Dsonar.login=你的Sonar令牌
  dependencies:
    - run_e2e_tests

关键注意:必须等待Vite服务完全启动后再执行Cypress,否则页面未加载插桩代码,window.__coverage__不会生成。

4. 适配CI环境的nyc配置

修改.nycrc.json,确保路径匹配CI环境的项目结构:

{
  "include": ["src/**/*.{js,jsx,ts,tsx}"],
  "exclude": ["node_modules", "test/**/*", "src/**/*.spec.{js,jsx,ts,tsx}"],
  "reporter": ["lcov", "json"],
  "report-dir": "./coverage",
  "temp-dir": "./.nyc_output"
}

5. 调试CI环境的覆盖率数据

在流水线测试步骤中添加调试命令,确认数据生成情况:

run_e2e_tests:
  stage: test
  script:
    # ...原有命令
    # 检查.nyc_output目录是否存在
    - ls -la .nyc_output/ || echo ".nyc_output目录未生成"

内容的提问来源于stack exchange,提问作者Stephane-Gon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:03:20