Skip to content

CI 流水线使用 Automated 测试

中等 约 45 分钟

你将构建什么

完整 CI 流水线配置 for GitHub 操作那个安装 dependencies, 运行测试使用 coverage, and 失败构建如果测试失败 or coverage drops below thresholds.

学习目标

  • 创建 GitHub 操作 workflow file
  • 运行测试 automatically on 推送 and 拉取请求
  • 缓存 dependencies for faster CI 运行
  • Upload coverage reports as artifacts
  • 理解 CI 测试 gates and 失败 handling

前置要求

  • GitHub 仓库使用测试
  • 已完成项目 1 or equivalent 测试 suite
  • 基础理解的 YAML

步骤

  1. 1

    创建 workflow file

    创建 .github/workflows/测试.yml 到定义 CI 流水线.

    代码
    name: Tests
    
    on:
      push:
        branches: [ main, develop ]
      pull_request:
        branches: [ main ]
    
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-node@v4
            with:
              node-version: '20'
              cache: 'npm'
          - run: npm ci
          - run: npm test -- --coverage
          - uses: actions/upload-artifact@v4
            with:
              name: coverage-report
              path: coverage/

    预期结果

    Workflow file 是创建.

  2. 2

    添加 coverage threshold enforcement

    配置 Jest 到失败如果 coverage drops below thresholds in 包.JSON.

    代码
    "jest": {
      "coverageThreshold": {
        "global": {
          "branches": 80,
          "functions": 80,
          "lines": 80,
          "statements": 80
        }
      }
    }

    预期结果

    CI 将失败如果 coverage 是 below 80%.

  3. 3

    测试流水线 locally

    运行相同 commands locally 到验证它们工作: npm CI && npm 测试 -- --coverage.

    预期结果

    局部运行 succeeds, matching 什么 CI 将做.

  4. 4

    推送 and 验证 CI 运行

    提交 and 推送到 触发 CI 流水线. Watch 操作 tab on GitHub 到 see 流水线执行.

    预期结果

    CI 流水线运行 and 通过 on GitHub.

  5. 5

    添加 parallel 测试 execution

    Optimize CI 通过运行测试 in parallel.

    代码
    - run: npm test -- --maxWorkers=2 --coverage

    预期结果

    CI 测试运行 faster 使用 parallel 工作者.

自己动手试试

你学到了什么

你学习到 设置 CI 流水线那个 automatically 运行测试 on 每个推送 and 拉取请求. CI acts as quality gate — failing 测试 or insufficient coverage 块合并. 这个 ensures code quality 是 maintained consistently 跨越 team.

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题