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

在Cypress中获取语言代码为DE的HTML对应JSON路径方法问询

在Cypress中按语言代码筛选JSON中的翻译HTML内容

你可以利用JavaScript数组的find()方法,根据language.code匹配目标语言,无需依赖数组索引来获取对应的HTML内容:

基础用法

// 定位语言代码为DE的翻译对象
const deTranslation = requestPromptsJsonRequest.translations.find(translation => 
  translation.language.code === 'DE'
);

// 提取对应的HTML内容(添加空值判断避免找不到时报错)
const deLangHtml = deTranslation ? deTranslation.html : '';

在Cypress请求流程中使用

如果是从接口响应中处理数据,可以这样写:

cy.request('你的接口地址')
  .then(response => {
    const targetTranslation = response.body.translations.find(item => 
      item.language.code === 'DE'
    );
    const targetHtml = targetTranslation?.html || ''; // 使用可选链操作符简化空值判断
    
    // 示例:验证获取到的HTML内容
    expect(targetHtml).to.eq('HTML I want');
  });

说明:

  • find()方法会遍历translations数组,返回第一个符合language.code === 'DE'条件的对象
  • 加入空值判断(三元运算符或可选链?.)是为了处理数组中没有DE语言项的情况,避免代码抛出Cannot read properties of undefined错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:35:56