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

使用Cypress校验元素selected属性值时出现异常的问题咨询

问题

我希望点击指定元素后,检查该元素的selected属性值是否为true。以下是我的实现代码:

function clickOnInterface(pos, interfaceName) {
    cy.get('[data-test="interface-list"]').contains(interfaceName).click();

    cy.get(`[data-test="interface-list"] ix-event-list-item:nth-child(${pos})`)
        .should("have.attr", "selected", "true");
}

但Cypress返回如下错误:

Timed out retrying after 20000ms: expected
'<ix-event-list-item.hydrated>' to have attribute 'selected' with the
value 'true', but the value was 'selected'

我对此感到困惑,因为我的元素属性明明设置为selected="true",想咨询该问题的原因及解决方法。

原因分析

这是因为你使用的ix-event-list-item是自定义元素,这类元素的布尔属性(比如selected)在DOM中的处理逻辑和标准HTML元素一致:当你在HTML中设置selected="true"时,浏览器会将该属性的实际值存储为"selected"——布尔属性只要存在就代表其值为true,DOM中会将属性名本身作为属性值保存,而非你写的"true"。

解决方法

提供三种可行的验证方案:

  • 方案1:仅验证属性存在
    对于布尔属性,只要属性存在就表示其值为true,直接检查属性是否存在即可:

    cy.get(`[data-test="interface-list"] ix-event-list-item:nth-child(${pos})`)
        .should("have.attr", "selected");
    
  • 方案2:匹配实际属性值
    既然DOM中实际存储的属性值是"selected",直接匹配该值:

    cy.get(`[data-test="interface-list"] ix-event-list-item:nth-child(${pos})`)
        .should("have.attr", "selected", "selected");
    
  • 方案3:检查DOM属性的布尔值
    如果ix-event-list-item元素通过JavaScript暴露了selected这个DOM属性(即可以通过element.selected访问),直接验证该布尔值更准确:

    cy.get(`[data-test="interface-list"] ix-event-list-item:nth-child(${pos})`)
        .should(($el) => {
            expect($el[0].selected).to.be.true;
        });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:48:30