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

如何在Cypress中检查HTML元素的ng-reflect-name属性值?

用Cypress验证ion-icon的ng-reflect-name属性值

场景说明

目标HTML元素如下,需要验证它的ng-reflect-name属性值是否为arrow-down-circle:

<ion-icon _ngcontent-wyk-c151="" slot="start" name="arrow-down-circle" color="primary" ng-reflect-name="arrow-down-circle" ng-reflect-color="primary" aria-label="arrow down circle" role="img" class="md ion-color ion-color-primary hydrated"></ion-icon>

你尝试的错误命令及问题

  • 错误命令1:

    cy.get(filter_popover).find('#ng-reflect-name').should('contain.text', 'arrow-down-circle');
    

    问题:#ng-reflect-name是按ID查找元素,但ng-reflect-name是元素属性而非ID,所以根本找不到目标元素。

  • 错误命令2:

    cy.get(filter_popover).find('[data-cy=btn_selectDesc]').invoke('attr', 'ng-reflect-name').should('contain.text', 'arrow-down-circle');
    

    问题:invoke('attr', 'ng-reflect-name')返回的是字符串类型的属性值,contain.text是用来断言元素文本内容的,不能用于字符串断言,所以会报错。

正确的验证方法

方法1:属性选择器直接匹配

如果能直接定位到目标ion-icon,用属性选择器匹配属性值,验证元素存在即可说明属性值符合预期:

cy.get(filter_popover)
  .find('ion-icon[ng-reflect-name="arrow-down-circle"]')
  .should('exist');

方法2:获取属性值后断言字符串

先定位到上层元素,再找到目标ion-icon,获取属性值后用字符串断言:

cy.get(filter_popover)
  .find('[data-cy=btn_selectDesc]')
  .find('ion-icon')
  .invoke('attr', 'ng-reflect-name')
  .should('eq', 'arrow-down-circle'); // 断言值完全相等
// 若只需验证包含指定内容,改用 .should('include', 'arrow-down-circle')

方法3:用have.attr直接断言(最简洁)

Cypress支持直接断言元素属性,无需额外调用invoke:

cy.get(filter_popover)
  .find('[data-cy=btn_selectDesc] ion-icon')
  .should('have.attr', 'ng-reflect-name', 'arrow-down-circle');

重要提示

ng-reflect-*是Angular开发环境下的调试属性,生产环境打包时会被移除。如果是针对生产环境的测试,建议改用元素原生属性(比如这里的name属性)来验证,更稳定:

cy.get(filter_popover)
  .find('[data-cy=btn_selectDesc] ion-icon')
  .should('have.attr', 'name', 'arrow-down-circle');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:01:36