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

使用Cypress intercept时cy.wait()超时问题求助

Cypress cy.wait() 超时无法捕获请求的排查与解决

参照YouTube教程编写Cypress intercept代码,运行时出现cy.wait() timed out waiting 5000ms for the 1st request to the route错误。代码与教程完全一致,页面可正常访问,点击Comments元素也正常,但cy.wait('@comments')一直挂起,无法捕获请求完成断言。

用户代码:

it.only('test api with simple intercept stubbing', () => {

        cy.visit('https://dummyapi.io/explorer');

        cy.intercept({
            path: 'data/v1/post/60d21af267d0d8992e610b8d/comment?limit=10'
        }).as('comments')

        cy.get('.flex > :nth-child(5)').click();
        cy.wait('@comments').then(intercept => {
            cy.log(JSON.stringify(intercept.response.body));
            expect(intercept.response.body.limit).equal(10)
        })
    })

解决方法

  • 拆分路径与查询参数:Cypress的path字段仅匹配URL的路径部分,不包含查询参数。你把?limit=10写在path里会导致匹配失败,需拆分配置:
    cy.intercept({
      path: 'data/v1/post/60d21af267d0d8992e610b8d/comment',
      query: { limit: '10' } // URL参数值为字符串类型,需保持一致
    }).as('comments')
    
  • 确认请求细节:打开Cypress的Network面板,查看点击后实际发起的请求:
    • 核对请求的完整URL、HTTP方法(默认cy.intercept只拦截GET请求)
    • 检查是否有请求延迟,可尝试延长超时时间:cy.wait('@comments', { timeout: 10000 })
  • 显式指定请求方法:如果实际请求不是GET,需在拦截配置中声明:
    cy.intercept({
      method: 'GET',
      path: 'data/v1/post/60d21af267d0d8992e610b8d/comment',
      query: { limit: '10' }
    }).as('comments')
    
  • 使用模糊匹配调试:若不确定完整路径,先用通配符捕获请求,再逐步精确匹配:
    cy.intercept('**/post/*/comment').as('comments')
    

内容的提问来源于stack exchange,提问作者D.Hodges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:13:23