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

如何在Cypress中测量XHR响应时长?POST请求时长获取异常排查

Cypress XHR响应时长测量及常见问题解决

嘿,我来帮你搞定这两个Cypress里的XHR时长相关问题!

1. 如何在Cypress中测量XHR的响应时长?

有两种实用的方法可以实现,根据你的需求选就行:

  • 方法一:手动记录时间差
    在请求发起时记个开始时间,响应回来后算差值,简单直接:

    let requestStartTime;
    
    // 拦截目标请求
    cy.intercept('POST', '/your-target-api', (req) => {
      requestStartTime = Date.now(); // 请求发起时记录时间
      req.continue((res) => {
        const responseDuration = Date.now() - requestStartTime;
        cy.log(`本次响应时长:${responseDuration}ms`);
        // 要是后续需要断言,还能把时长存进响应对象里
        res.responseDuration = responseDuration;
      });
    });
    
    // 触发请求的操作,比如点击按钮
    cy.get('#trigger-btn').click();
    
  • 方法二:利用Cypress自带的timings属性
    Cypress 10+版本的拦截器会返回timings对象,里面包含了请求各阶段的时间戳,直接算差值更准确:

    // 给请求起个别名方便后续等待
    cy.intercept('POST', '/your-target-api').as('postRequest');
    
    // 触发请求
    cy.get('#trigger-btn').click();
    
    // 等待请求完成后获取时长
    cy.wait('@postRequest').then((interception) => {
      const { timings } = interception;
      // responseStart是响应开始接收的时间,responseEnd是响应接收完成的时间
      const responseDuration = timings.responseEnd - timings.responseStart;
      cy.log(`响应时长:${responseDuration}ms`);
      
      // 还能直接做断言,比如要求时长不超过500ms
      expect(responseDuration).to.be.lessThan(500);
    });
    

2. 解决xhr.response.duration为空但response.body正常的问题

这个坑我之前也踩过!问题出在Cypress的响应对象里根本没有duration这个属性,你看到的response.body是默认存在的,但时长数据藏在timings对象里,不是直接挂在response下面的。

具体解决方案:

方案一:访问正确的timings属性

通过cy.wait()拿到拦截的请求对象后,从timings里计算时长:

cy.intercept('POST', '/your-target-api').as('postRequest');

cy.get('#trigger-btn').click();

cy.wait('@postRequest').then((interception) => {
  // 正确获取响应时长的方式
  const responseDuration = interception.timings.responseEnd - interception.timings.responseStart;
  cy.log(`响应时长:${responseDuration}ms`); // 现在能正常打印了
  cy.log(JSON.stringify(interception.response.body)); // 响应体依然正常输出
});

方案二:手动给response添加duration属性

如果你习惯了用response.duration的写法,可以在拦截时手动把时长挂到response上:

cy.intercept('POST', '/your-target-api', (req) => {
  req.continue((res) => {
    // 计算时长并添加到response对象
    res.duration = res.timings.responseEnd - res.timings.responseStart;
  });
}).as('postRequest');

cy.get('#trigger-btn').click();

cy.wait('@postRequest').then((interception) => {
  cy.log(JSON.stringify(interception.response.duration)); // 现在就能拿到有效值了
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 06:57:47