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

Angular项目Github无头模式Cypress调用cy.visit()报404本地正常求助

Github Actions无头模式下Cypress访问Angular页面返回404问题

问题详情

  • 在Github Actions无头模式运行Cypress测试时,cy.visit('/page')触发404错误,错误提示:

CypressError: 'cy.visit()' failed trying to load:

http://localhost:4200/page

  • 本地环境(无论无头/有头模式)测试完全正常
  • 目标为Angular应用,已通过通配符路由处理所有路径,理论上不存在404场景,且所有页面访问均出现该问题
  • 使用版本:"cypress": "^10.6.0"
  • 已在integration.config.ts中配置baseUrl为http://localhost:4200

排查与解决建议

1. 确保Angular应用在CI环境中完全启动

Github Actions中ng serve可能未完全就绪,Cypress就开始执行测试:

  • 借助wait-on工具等待应用启动完成,修改启动命令:
    npm run start & npx wait-on http://localhost:4200
    
  • 或在Cypress配置中延长页面加载超时时间:
    // integration.config.ts
    export default defineConfig({
      e2e: {
        pageLoadTimeout: 120000, // 调整为120秒
        // 其他原有配置
      },
    });
    

2. 验证Angular路由配置的环境一致性

确认CI环境中Angular的路由逻辑与本地一致:

  • 检查通配符路由是否正确配置:
    // app-routing.module.ts
    const routes: Routes = [
      // 业务路由
      { path: '**', component: YourFallbackComponent }, // 确保该路由存在且生效
    ];
    
  • 若CI环境运行的是生产构建,需确认服务器配置支持SPA路由(比如Nginx需配置try_files $uri $uri/ /index.html;)

3. 确认Cypress的baseUrl配置生效

在测试代码中添加日志验证实际配置:

cy.log('当前baseUrl:', Cypress.config('baseUrl'));

确保输出为http://localhost:4200,避免配置未被正确加载。

4. 检查CI环境的端口可用性

在测试前添加端口连通性检查:

curl http://localhost:4200

确认端口未被占用、网络权限正常。

5. 升级Cypress版本

Cypress 10.6.0存在部分无头模式兼容性问题,尝试升级至12.x或13.x稳定版本,大概率修复此类场景的适配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:55:48