⚠️ Alpha内测版本警告:此为早期内部构建版本,尚不完整且可能存在错误,欢迎大家提Issue反馈问题或建议
Skip to content

11.2.2 质量检查:测试/构建/安全扫描

一句话破题

质量门禁通过自动化检查确保代码符合标准,不合格的代码无法合并到主分支。

核心价值

配置质量门禁能让你:

  • 自动拦截有问题的代码
  • 减少人工 Review 的负担
  • 保持代码库的整洁和一致性

完整的质量检查配置

yaml
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  # 类型检查
  typecheck:
    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 run typecheck

  # 代码规范检查
  lint:
    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 run lint

  # 单元测试
  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
      - name: Upload coverage
        uses: codecov/codecov-action@v3

  # 构建验证
  build:
    runs-on: ubuntu-latest
    needs: [typecheck, lint, test]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm run build

依赖安全扫描

yaml
  # 依赖漏洞扫描
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run npm audit
        run: npm audit --audit-level=high
      
      # 或使用 Snyk
      - name: Run Snyk
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}

配置分支保护规则

在 GitHub 仓库设置中启用分支保护:

Settings → Branches → Branch protection rules → Add rule

勾选:
☑ Require a pull request before merging
☑ Require status checks to pass before merging
  └─ 选择: typecheck, lint, test, build
☑ Require branches to be up to date before merging

检查失败时的处理

yaml
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - name: Run ESLint
        run: npm run lint
        continue-on-error: false  # 失败时阻断流程
      
      # 可选:上传错误报告
      - name: Upload lint report
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: lint-report
          path: lint-results.json

避坑指南

新手最容易犯的错

  1. 检查太多导致 CI 时间过长(应并行执行)
  2. 没有配置分支保护规则(检查可被绕过)
  3. 忽略安全扫描结果
  4. 测试覆盖率阈值设置过高导致频繁失败