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

如何在CircleCI中运行React应用以供Cypress E2E测试访问?

解决CircleCI中Cypress无法连接React应用的问题

问题根源

CircleCI的每个run步骤执行完毕后,当前shell会退出,通过&后台启动的进程会被系统发送SIGHUP信号终止,导致后续测试步骤执行时,React应用服务器已经停止运行。这就是后台启动服务器后测试失败、wait-on一直等待的核心原因。

解决方案

方案1:整合服务启动与测试流程(推荐)

将启动服务器、等待服务就绪、运行Cypress测试放在同一个run步骤中,确保后台进程不会被提前终止:

修改CircleCI配置的steps部分:

steps:
  - checkout:
      path: ~/project
  - run:
      name: Install dependencies
      command: npm ci
  - run:
      name: Build React app
      command: npm run build
  - run:
      name: Verify build output
      command: ls -la ./dist # 确认dist目录存在且有文件
  - run:
      name: Serve app and run Cypress tests
      command: |
        npm install -g http-server
        http-server ./dist/ -a 0.0.0.0 -p 3000 &
        npx wait-on http://127.0.0.1:3000
        npx cypress run

方案2:使用nohup让服务器进程脱离shell

通过nohup启动服务器,使其不受当前shell退出的影响:

steps:
  - checkout:
      path: ~/project
  - run:
      name: Install dependencies
      command: npm ci
  - run:
      name: Build React app
      command: npm run build
  - run:
      name: Install http-server
      command: npm install -g http-server
  - run:
      name: Serve React app
      command: |
        nohup http-server ./dist/ -a 0.0.0.0 -p 3000 > server.log 2>&1 &
  - run:
      name: Wait for server to start
      command: npx wait-on http://127.0.0.1:3000
  - run:
      name: Run cypress tests
      command: npx cypress run

额外注意事项

  • 绑定服务器到0.0.0.0而非127.0.0.1,确保容器内所有网络接口都能访问服务,提升兼容性。
  • 移除npm ci的--ignore-scripts参数,避免依赖包的安装脚本被跳过,导致Cypress或其他工具无法正常工作。
  • 增加Verify build output步骤,确认dist目录存在且包含正确的构建产物,避免因构建失败导致服务器无内容可提供。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:06:55