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

Cypress intercept与wait在GitHub Actions中失效问题求助

解决GitHub Actions中Cypress等待请求超时问题

问题现象

本地测试全部正常通过,但在GitHub Actions执行时,某测试失败,报错信息如下:

CypressError: Timed out retrying after 60000ms:
cy.wait() timed out waiting 60000ms for the 1st request to the route:
addCustomerMutation. No request ever occurred.

测试代码

// IMPORTS

cy.intercept('POST', URL, (req) => {
  delete req.headers['if-none-match'];
  const addCustomerOp = 'addCustomerMutation';
  const { body } = req;
  if (body.hasOwnProperty('operationName' && body.operationName === addCustomerOp) {
    req.alias = addCustomerOp;
    req.reply({ data: addCustomer });
   }
});

// 填写表单

cy.get('[data-testid="customer-save-button"]').click();

cy.wait('@addCustomerMutation', { timeout: 60000 })
  .its('request.body.variables')
  .should('deep.equal', {
    clientId: 'client_id',
    customer: {
      firstName: 'test',
      lastName: 'tester',
      email: 'test@test.com',
      phone: {
        name: '',
        number: '(531) 731-3151',
       },
       alternatePhones: [],
    },
});

已尝试的无效方法

  • 将Cypress版本回退至6.4和6.8
  • 在cy.wait()后添加额外断言
  • 将超时时间增加至100000ms

GitHub Actions工作流配置

jobs:
  test:
    concurrency: test # 避免同时运行不同分支的测试
    runs-on: ubuntu-latest
    container: cypress/browsers
    steps:
      - name: 拉取代码
        uses: actions/checkout@v3
      - name: 配置npm token
        run: |
            echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN_RO }}" >> ./.npmrc
      - name: 配置Node.js环境
        uses: actions/setup-node@v3
        with:
            node-version-file: '.nvmrc'
            registry-url: 'https://registry.npmjs.org'
            cache: npm
      - name: 安装依赖
        run: npm ci
      - name: 运行测试
        uses: cypress-io/github-action@v5
        with:
          env: username=${{ secrets.CYPRESS_TEST_USER }},password=${{ secrets.CYPRESS_TEST_PASSWORD }},REACT_APP_URI=${{ secrets.REACT_APP_URI }}
          install-command: | # TODO: 安装前检查node modules
            npm ci --production=false
          browser: chrome
          spec: cypress/integration/*.spec.*
          start: npm run start:cypress
          wait-on: npx wait-on http://localhost:3000
      - name: 上传测试截图
        uses: actions/upload-artifact@v3
        if: failure()
        with:
          name: cypress-screenshots
          path: cypress/screenshots
      # 测试视频始终会被捕获,因此使用always()条件
      - name: 上传测试视频
        uses: actions/upload-artifact@v3
        if: always()
        with:
          name: cypress-videos
          path: cypress/videos

解决方案

1. 修复拦截逻辑的语法错误

测试代码中cy.intercept的判断条件存在语法错误:
原代码:body.hasOwnProperty('operationName' && body.operationName === addCustomerOp)
正确写法:

if (body.operationName && body.operationName === addCustomerOp) {

原错误导致拦截无法匹配到目标请求,是超时的核心原因。

2. 优化应用启动等待逻辑

wait-on仅检查端口是否开放,但应用可能未完全初始化。可以:

  • 延长等待时间:wait-on http://localhost:3000 --timeout 120000
  • 在测试开头添加元素等待:cy.get('[data-testid="app-ready"]').should('be.visible'),确保应用完全加载后再执行测试步骤。

3. 添加拦截调试日志

在cy.intercept中添加日志,确认请求是否被捕获:

cy.intercept('POST', URL, (req) => {
  delete req.headers['if-none-match'];
  const addCustomerOp = 'addCustomerMutation';
  const { body } = req;
  console.log('请求operationName:', body?.operationName);
  if (body.operationName && body.operationName === addCustomerOp) {
    req.alias = addCustomerOp;
    console.log('匹配到addCustomerMutation,设置别名');
    req.reply({ data: addCustomer });
   }
});

通过GitHub Actions的日志输出,确认请求是否到达拦截器。

4. 禁用Chrome缓存

GitHub Actions环境中Chrome的缓存可能导致请求未正常发送,在Cypress配置中添加禁用缓存的参数:

// cypress.config.js
module.exports = {
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser = {}, launchOptions) => {
        if (browser.name === 'chrome') {
          launchOptions.args.push('--disable-cache');
          launchOptions.args.push('--disable-application-cache');
          return launchOptions;
        }
      });
    },
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:31:22