如何在 GitHub Actions 的 strategy.matrix 中动态注入 Cypress 标签?

解读

国内 CI 普遍采用 GitHub Actions,而 Cypress 在大型前端仓库里往往按“标签(grep/tag)”拆分用例集,以缩短流水线耗时。
面试官问“动态注入”,核心想验证两点:

  1. 你能否在 workflow 触发阶段 就拿到“本次改动需要跑哪些标签”的清单;
  2. 你能否把这份清单 无损地塞进 strategy.matrix 里,让 Job 并发跑,而不是写死 10 几个 job。

如果候选人只能回答“把标签写死在 yaml 里”,会被直接判定为“初级”;
若能给出“文件 diff + 动态矩阵”方案,并解释清楚 JSON 转义、产量上限、缓存 key 的连锁影响,才算“高级/专家”。

知识点

  1. strategy.matrix 只接受「数组」语法,数组内容必须在 job 启动前完全静态化;
  2. 想让矩阵动态,只能借助 fromJSON(needs.xxx.outputs.xxx),把上游 job 的输出当成数组;
  3. 上游 job 里用 core.setOutput 把字符串数组序列化为 JSON,注意单引号、双引号、转义符;
  4. 拿到变更文件列表的三种国内常用办法:
    • git diff HEAD~1(push 场景)
    • git diff ${{ github.event.pull_request.base.sha }}(PR 场景)
    • 使用 paths-filter Action,支持 globs 与自定义映射;
  5. 根据文件路径→反向映射到 Cypress 标签,常见做法:
    • 维护 cypress-tags.json 映射表,key 是目录,value 是标签数组;
    • 用 jq 做集合合并与去重;
  6. 产量上限:GitHub 免费组织并发 20,矩阵笛卡尔积最大 256,需 slice 或 parallel 降级;
  7. 缓存:动态矩阵导致 cache key 也要跟着标签走,否则会出现“命中了旧缓存,用例没跑全”的线上事故;
  8. 回退策略:若动态计算失败,必须兜底跑 smoke 标签,防止空矩阵直接跳过测试。

答案

  1. 在仓库根目录放置 cypress-tags.json,内容示例:
    { "modules/order": ["@order","@smoke"], "modules/user": ["@user","@smoke"] }

  2. 编写 .github/workflows/detect-tags.yml(上游 job):

    name: Detect Cypress Tags
    on:
      pull_request:
        paths-ignore: ['docs/**','*.md']
    jobs:
      detect:
        runs-on: ubuntu-latest
        outputs:
          tags: ${{ steps.calc.outputs.tags }}
        steps:
          - uses: actions/checkout@v4
            with:
              fetch-depth: 0
          - id: changes
            uses: dorny/paths-filter@v2
            with:
              filters: |
                order: ['modules/order/**']
                user:  ['modules/user/**']
          - id: calc
            run: |
              tags='["@smoke"]'   # 兜底
              if [[ "${{ steps.changes.outputs.order }}" == "true" ]]; then
                tags=$(echo "$tags" | jq '. += ["@order"]')
              fi
              if [[ "${{ steps.changes.outputs.user }}" == "true" ]]; then
                tags=$(echo "$tags" | jq '. += ["@user"]')
              fi
              tags=$(echo "$tags" | jq 'unique')
              echo "tags=$tags" >> $GITHUB_OUTPUT
    
  3. 编写真正执行测试的 cypress-matrix.yml:

    name: Cypress Dynamic Matrix
    on:
      workflow_run:
        workflows: ['Detect Cypress Tags']
        types:
          - completed
    jobs:
      e2e:
        if: ${{ github.event.workflow_run.conclusion == 'success' }}
        runs-on: ubuntu-latest
        strategy:
          fail-fast: false
          matrix:
            tag: ${{ fromJSON(needs.detect.outputs.tags) }}
        steps:
          - uses: actions/checkout@v4
          - uses: cypress-io/github-action@v6
            with:
              install-command: npm ci
              start: npm start
              wait-on: 'http://localhost:3000'
              command: npm run cypress:run -- --env grepTags="${{ matrix.tag }}"
          - uses: actions/upload-artifact@v3
            if: failure()
            with:
              name: cypress-screenshots-${{ matrix.tag }}
              path: cypress/screenshots
    
  4. 若矩阵计算结果为空,detect job 里强制塞入 @smoke,保证矩阵最小长度为 1,避免 GitHub Actions 报“Matrix must be non-empty”。

拓展思考

  1. 当仓库达到 monorepo 级别(>500 模块),cypress-tags.json 手工维护成本高,可改为:

    • 在 cypress.config.js 里给每个 spec 文件写 tag: [...],
    • 用 cypress-grep 的 npx cypress grep --list 导出所有标签,
    • 结合 git diff 做标签交集,实现“全自动”注入;
  2. 如果团队使用 Cypress Cloud,可把矩阵粒度从“标签”下沉到“test suite”,利用 parallelizationKey 让 GitHub Actions 只负责拆 spec 文件,Cypress Cloud 负责负载均衡,进一步压缩总耗时;

  3. 国内网络拉取 Cypress 二进制经常超时,可在 detect job 里把 CYPRESS_INSTALL_BINARY=https://npmmirror.com/... 作为输出变量,一并传给下游 job,保证矩阵里每个节点都能复用同一镜像缓存,避免重复下载;

  4. 安全:动态输出注入矩阵时,务必 jq 转义,防止 PR 里夹带恶意字符串造成命令注入;

  5. 预算:GitHub 付费组织并发 500,但矩阵爆炸仍可能瞬间跑满,建议加 rate-limit 步骤,按标签优先级分批触发,夜间再补跑低优标签,平衡成本与覆盖率。