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

Cypress技术问题:ArrayBuffer为空,请求返回数据却解析失败

解决Cypress请求arraybuffer返回空及测试逻辑问题

核心问题分析

  1. arraybuffer解析错误:你设置了responseType: 'arraybuffer',但直接用JSON.parse(response.body)会导致解析失败——arraybuffer不能直接转JSON,且请求头里的Content-Type: application/json和实际页面返回类型不匹配(Contentful托管的页面大概率是HTML,而非JSON)。
  2. 异步逻辑错误:你在cy.get('@pagesUrls').each(...)之后直接判断errores.length,但Cypress命令是异步执行的,此时遍历还未完成,errores数组仍为空。
  3. 断言捕获失效:Cypress的should断言是异步的,try/catch无法捕获它的失败,因为断言是在Cypress命令队列中执行的。

具体修复方案

1. 修正请求配置与响应解析

  • 移除错误的Content-Type请求头(页面请求无需该头,除非明确接口返回JSON)。
  • 将arraybuffer转成字符串后再处理,若页面是HTML,直接检查字符串内容即可,无需转JSON。

2. 调整异步错误收集逻辑

在each遍历完成后再处理错误,确保所有请求执行完毕后再判断结果。

3. 正确捕获断言失败

改用同步的字符串检查替代异步断言,或通过链式调用处理断言失败。

修改后的完整代码

import { getPagesFromContentful } from '../../support/getPagesFromContentful';
import '../../support/commands';

describe('Mi prueba', () => {
  beforeEach(() => {
    cy.clearLocalStorage();
    cy.clearCookies();
  });
 
  it('prueba pagina parte 1', () => {
    getPagesFromContentful().then((pagesUrls) => {
      const errores = [];

      // 遍历所有URL,确保所有请求完成后再处理结果
      cy.wrap(pagesUrls).each((url) => {
        cy.request({
          url: url,
          method: 'GET',
          failOnStatusCode: false,
          responseType: 'arraybuffer',
        }).then((response) => {
          // 将arraybuffer解码为UTF-8字符串
          const decoder = new TextDecoder('utf-8');
          const bodyContent = decoder.decode(response.body);

          // 检查页面是否包含错误标识
          if (bodyContent.includes('error-page')) {
            const errorMensaje = `Error en la URL ${url}: 页面包含错误标识`;
            errores.push(errorMensaje);
            cy.log(errorMensaje);
          }
        }).catch((requestError) => {
          // 捕获请求本身的错误(如网络问题)
          const errorMensaje = `请求URL ${url}失败: ${requestError.message}`;
          errores.push(errorMensaje);
          cy.log(errorMensaje);
        });
      }).then(() => {
        // 所有请求完成后统一检查错误
        if (errores.length > 0) {
          const errorMessage = `Se encontraron ${errores.length} errores:\n\n${errores.join('\n\n')}`;
          cy.log(errorMessage);
          throw new Error(errorMessage);
        }
      });
    });
  });
});

额外优化建议

  • 如果页面是HTML,可直接去掉responseType: 'arraybuffer',使用默认的text类型,此时response.body就是字符串,无需解码。
  • 若需要验证HTTP状态码,可在cy.request回调中添加expect(response.status).to.be.oneOf([200, 304])类断言,将状态码错误也纳入错误收集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:33:23