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

如何配置Github Actions运行前后端后执行Cypress/Jest测试不阻塞

核心问题原因

你当前配置的npm run start:prod(后端启动)和npm run start(前端启动)都是前台阻塞进程,启动后会持续占据当前命令行会话,不会主动退出,因此GitHub Actions会判定该步骤未执行完成,永远无法进入后续步骤。

调整后完整配置

name: test
on: [push]
env:
  CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  OTHER_SECRETS: ${{ secrets.otherSecrets }}
  # 替换为你实际的后端、前端服务端口
  BACKEND_PORT: 3000
  FRONTEND_PORT: 4200
jobs:
  cypress-run:
    runs-on: macos-11
    steps:
      - name: Setup Node.js environment
        uses: actions/setup-node@v2.5.0
        with:
          node-version: '16.13.0'
      - name: Checkout
        uses: 'actions/checkout@v2'

      # 新增:缓存node_modules,减少后续CI依赖安装耗时
      - name: Cache backend dependencies
        uses: actions/cache@v3
        with:
          path: server/node_modules
          key: ${{ runner.os }}-backend-node-${{ hashFiles('server/package-lock.json') }}
      - name: Cache frontend dependencies
        uses: actions/cache@v3
        with:
          path: node_modules
          key: ${{ runner.os }}-frontend-node-${{ hashFiles('package-lock.json') }}

      - name: "Build & Start Backend"
        run: |
          cd server &&
          npm install &&
          npm run build &&
          # 末尾加&将进程放到后台运行
          npm run start:prod &
          # 等待后端服务就绪,最多等60秒
          for i in {1..60}; do
            curl -s http://localhost:${{ env.BACKEND_PORT }} > /dev/null && break
            sleep 1
          done
      - name: "Build & Start Frontend"
        run: |
          npm install &&
          npm run build &&
          # 末尾加&将进程放到后台运行
          npm run start &
          # 等待前端服务就绪,最多等60秒
          for i in {1..60}; do
            curl -s http://localhost:${{ env.FRONTEND_PORT }} > /dev/null && break
            sleep 1
          done
      - name: Cypress run
        uses: cypress-io/github-action@v2
        with:
          record: true
          browser: chrome
      - name: "Run Jest Tests"
        run: |
            cd server &&
            npm run test

关键改动说明

  • 后台启动逻辑:在服务启动命令末尾添加&将进程放到后台,当前步骤无需等待进程退出即可结束,进入后续环节
  • 服务就绪检查:用循环curl的方式主动探测服务端口,比固定sleep更可靠,不会出现服务还没启动完就跑测试的问题,也不会浪费多余等待时间
  • 之前你尝试的方法无效是因为你把&& curl写在了阻塞的启动命令之后,系统需要等启动命令退出才会执行curl,自然永远不会生效
  • CI运行结束后会自动清理所有后台进程,不需要手动处理服务关闭逻辑

内容的提问来源于stack exchange,提问作者CT100

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:15:04