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

Cypress测试:获取动态ID元素的value属性值方法

问题:Cypress中获取动态ID输入框的value属性值用于断言

需求场景

  • 页面有10个带动态ID的行,需逐行展开后,检查输入框value属性中是否包含文件名cypress.png
  • 需要遍历所有行完成校验

当前问题

  • 无法获取动态ID输入框的value属性值,无法与上传文件名做对比
  • 使用invoke(attr, value)方法无效,调用时会逐字符返回值而非完整字符串

相关HTML代码

<div class="bx--text-input__field-outer-wrapper">
  <div class="bx--text-input__field-wrapper">
    <input id="scenario-name-63add9a59b4cb45bc67d7bab" 
      type="text" 
      class="bx--text-input bx--form-item" 
      readonly="" 
      value="cypress1.png">
  </div>
</div>

现有Cypress代码

// 展开所有行 - 我知道可以用批量点击,但希望用这个循环逻辑实现
cy.get('.bx--table-expand__svg')
  .each(function($expand){
    cy.wrap($expand).click()
  })

// 这里能打印每行的ID,但拿不到value属性值
cy.get('input[id*=scenario-]')
  .each(function($scn,index,$scenarios){
    cy.log($scn,index)
  })

// 尝试用INVOKE,但返回的是单个字符而非完整值

解决方案

方法1:在.each()回调中直接使用jQuery方法

Cypress封装了jQuery,.each()的回调参数$scn是jQuery对象,可直接调用attr()获取属性值:

cy.get('input[id*=scenario-]')
  .each(($scn, index) => {
    // 获取input的value属性值(适用于readonly场景)
    const inputValue = $scn.attr('value');
    cy.log(`第${index+1}行的value值:`, inputValue);
    
    // 断言是否包含目标文件名
    expect(inputValue).to.include('cypress.png');
  });

方法2:使用Cypress的invoke()正确写法

保持链式调用风格时,注意invoke()的第二个参数要传字符串'value':

cy.get('input[id*=scenario-]')
  .each(($scn, index) => {
    cy.wrap($scn)
      .invoke('attr', 'value') // 第二个参数必须是字符串'value'
      .then(value => {
        cy.log(`第${index+1}行的value属性:`, value);
        expect(value).to.include('cypress.png');
      });
  });

方法3:如果是可编辑输入框,获取实时值

若输入框非只读,需获取用户输入后的实时值,改用val()方法:

cy.get('input[id*=scenario-]')
  .each(($scn, index) => {
    const inputValue = $scn.val(); // 获取输入框当前实时值
    cy.log(`第${index+1}行的当前值:`, inputValue);
    
    expect(inputValue).to.include('cypress.png');
  });

问题原因说明

之前使用invoke出现逐字符返回的情况,大概率是参数传错——没有给value加引号,导致Cypress把value当成变量而非属性名,引发错误调用逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:01:00