如何合并 Jest 与 Cypress 的覆盖率并上传至 Codecov?

解读

国内主流前端项目普遍采用 Jest 做单测、Cypress 做 E2E,两套工具各自生成 coverage-final.json。面试官想知道候选人是否:

  1. 理解 Istanbul 的覆盖率数据格式与合并原理
  2. 能在 CI(GitHub Actions / GitLab CI / Jenkins)里把两份报告合成一份,再上传到国内可访问的 Codecov 平台
  3. 知道如何排除冲突路径、避免重复计算、保证 Source Map 一致
  4. 熟悉国内网络环境下上传失败时的兜底方案(如使用 Codecov 国内镜像或自建 MinIO + 脚本上报)

知识点

  • Istanbul 的 nyc 与 c8 格式差异、coverage-final.json 结构
  • nyc merge / nyc report --reporter=lcov 命令行用法
  • babel-plugin-istanbul 与 @cypress/code-coverage 的注入时机
  • GitHub Actions 缓存策略(actions/cache@v3 缓存 node_modules 与 .nyc_output)
  • Codecov 上传 token 在开源仓库与私有仓库的区别;国内网络下 codecov-action@v3 的 fail_ci_if_error 与 retry 参数
  • 路径别名(如 @/components)在合并时导致重复模块的解决方案:nyc 的 --exclude 与 --extension 参数
  • monorepo 场景下子包报告的合并策略:lerna + nyc 的 --cwd 与 --reporter=json
  • 覆盖率门禁(coverage threshold)在 CI 中的卡点配置,防止“合并后总量达标但单测或 E2E 各自不达标”的漏洞

答案

  1. 依赖安装
    项目根目录执行:
    npm i -D jest @cypress/code-coverage nyc codecov

  2. 配置 Jest 注入覆盖率
    jest.config.js

    module.exports = {
      collectCoverage: true,
      coverageDirectory: 'coverage-jest',
      coverageReporters: ['json', 'lcov'],
      testEnvironment: 'jsdom',
      transform: {
        '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest'
      }
    };
    

    babel.config.js 确保带 babel-plugin-istanbul:

    module.exports = {
      plugins: ['istanbul']
    };
    
  3. 配置 Cypress 注入覆盖率
    cypress/support/e2e.js 顶部加入:

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

    cypress.config.js

    const { defineConfig } = require('cypress');
    module.exports = defineConfig({
      e2e: {
        baseUrl: 'http://localhost:3000',
        setupNodeEvents(on, config) {
          require('@cypress/code-coverage/task')(on, config);
          return config;
        }
      }
    });
    
  4. 本地脚本合并
    package.json 新增:

    "scripts": {
      "test:unit": "jest",
      "test:e2e": "cypress run",
      "cov:merge": "nyc merge coverage-jest coverage-cypress/.nyc_output && nyc report --reporter=lcov --report-dir=coverage-merged",
      "cov:upload": "codecov -f coverage-merged/lcov.info"
    }
    

    运行:
    npm run test:unit
    npm run test:e2e
    npm run cov:merge
    npm run cov:upload

  5. CI 完整示例(GitHub Actions)

    name: CI
    on: [push, pull_request]
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - uses: actions/setup-node@v3
            with:
              node-version: 18
              cache: 'npm'
          - run: npm ci
          - run: npm run test:unit
          - run: npm run test:e2e
          - run: npm run cov:merge
          - name: Upload to Codecov
            uses: codecov/codecov-action@v3
            with:
              file: ./coverage-merged/lcov.info
              token: ${{ secrets.CODECOV_TOKEN }}
              fail_ci_if_error: true
              verbose: true
    
  6. 国内网络兜底
    若上传超时,可在 CI 里加 retry:

    - run: |
        for i in {1..3}; do
          codecov -f coverage-merged/lcov.info -t ${{ secrets.CODECOV_TOKEN }} && break || sleep 15
        done
    

    或改用 Codecov 国内镜像:

    - run: codecov -u https://api.codecov.io -f coverage-merged/lcov.info
    
  7. 门禁校验
    package.json 追加:

    "nyc": {
      "branches": 80,
      "lines": 80,
      "functions": 80,
      "statements": 80
    }
    

    CI 最后一步:

    - run: nyc check-coverage --branches 80 --lines 80 --functions 80 --statements 80
    

拓展思考

  • 如果项目使用 Vite,可改用 c8 代替 babel-plugin-istanbul,此时 Cypress 端需把 @cypress/code-coverage 换成 vite-plugin-istanbul,合并步骤不变,但注意 c8 生成的 coverage-final.json 与 nyc 格式完全兼容,可直接 nyc merge。
  • 在微前端场景,子应用独立仓库,如何把各子应用的 Jest=unit 与主应用的 Cypress=E2E 覆盖率再二次聚合?思路是把各子应用上传的 coverage.json 下载到主仓库,再用 nyc merge 汇总,最后一次性上传到 Codecov,并在 PR 评论里展示增量覆盖率。
  • 国内私有 GitLab 无法访问外网时,可自建 Codecov Enterprise 或使用开源替代 codecov-self-hosted,上传地址改为内网域名即可;同时把 lcov 转成 cobertura.xml 方便 GitLab 原生覆盖率图表解析。