前端自动化测试框架Cypress(九)--获取元素属性.text() .attribute()

25 篇文章 18 订阅
25 篇文章 18 订阅

安装插件cypress-commands

npm install cypress-commands

将cypress-commands导入项目中 cypress/support/index.js

import 'cypress-commands'

.text()
正确用法

<div>Catastrophic Cat</div>
<div>Dramatic Dog</div>
<div>Amazing Ant</div>
// yields [
//   "Catastrophic Cat",
//   "Dramatic Dog",
//   "Amazing Ant"
// ]
cy.get('div').text();
<div> Extravagant &nbsp;
  Eagle            </div>

不省去空格

// yields "Extravagant Eagle"
cy.get('div').text()
// or
cy.get('div').text({ whitespace: 'simplify' });

省去空格不省去换行符(\n)

// yields "Extravagant\nEagle"
cy.get('div').text({ whitespace: 'keep-newline' });

不省去空格

// yields "Extravagant  \n  Eagle"
cy.get('div').text({ whitespace: 'keep' });

默认情况下,只会产生主题本身的文本。使用此选项还可以获得基础元素的文本。

<div class="grandparent">
  Grandma Gazelle
  <div class="parent">
    Mother Meerkat
    <div class="child">
      Son Scorpion
    </div>
  </div>
  <div class="parent">
    Father Fox
  </div>
</div>

不包含子元素的文本

// yields "Grandma Gazelle"
cy.get('.grandparent')
  .text();
// or
// yields "Grandma Gazelle"
cy.get('.grandparent')
  .text({ depth: 0 });

获取所有子元素的文本(text)并已空格连接

// yields "Grandma Gazelle Mother Meerkat Father Fox"
cy.get('.grandparent')
  .text({ depth: 1 });

当定位不唯一时获取所有元素的所有子元素的文本(text)并已空格连接生成一个字符串组

// yields [
//   "Mother Meerkat Son Scorpion",
//   "Father Fox"
// ]
cy.get('.parent')
  .text({ depth: 1 });

获取所有后代元素的文本并已空格连接

// yields "Grandma Gazelle Mother Meerkat Father Fox Son Scorpion"
cy.get('.grandparent')
  .text({ depth: Infinity });

.attribute() 获取元素属性值
语法:

.attribute(attribute)
.attribute(attribute, options)

正确用法

cy.get('a').attribute('href')

获取alt属性值

<img src='./images/tiger.jpg' alt='Teriffic tiger'>
// yields "Teriffic Tiger"
cy.get('img').attribute('alt');

获取type属性值

// yields [
//     "text",
//     "submit"
// ]
cy.get('input').attribute('type');

获取data-attribute属性值

<div data-attribute=" Extravagant &nbsp;
  Eagle            "></div>

默认省去空格

// yields "Extravagant Eagle"
cy.get('div').attribute('data-attribute');

省去空格–通默认一直

// yields "Extravagant Eagle"
cy.get('div').attribute('data-attribute', { whitespace: 'simplify' });

省去空格保留换行符(\n)

// yields "Extravagant\nEagle"
cy.get('div').attribute('data-attribute', { whitespace: 'keep-newline' });

不省去空格

// yields " Extravagant  \n  Eagle            "
cy.get('div').attribute('data-attribute', { whitespace: 'keep' });

更多系列文章:https://blog.csdn.net/qq_33676825

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值