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

安装插件cypress-commands

1
npm install cypress-commands

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

1
import 'cypress-commands'

.text()
正确用法

1
2
3
<div>Catastrophic Cat</div>
<div>Dramatic Dog</div>
<div>Amazing Ant</div>
1
2
3
4
5
6
// yields [
//   "Catastrophic Cat",
//   "Dramatic Dog",
//   "Amazing Ant"
// ]
cy.get('div').text();

1
2
<div> Extravagant  
  Eagle            </div>

不省去空格

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

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

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

不省去空格

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

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

1
2
3
4
5
6
7
8
9
10
11
12
<div class="grandparent">
  Grandma Gazelle
  <div class="parent">
    Mother Meerkat
    <div class="child">
      Son Scorpion
    </div>
  </div>
  <div class="parent">
    Father Fox
  </div>
</div>

不包含子元素的文本

1
2
3
4
5
6
7
// yields "Grandma Gazelle"
cy.get('.grandparent')
  .text();
// or
// yields "Grandma Gazelle"
cy.get('.grandparent')
  .text({ depth: 0 });

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

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

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

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

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

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

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

1
2
.attribute(attribute)
.attribute(attribute, options)

正确用法

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

获取alt属性值

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

获取type属性值

1
2
3
4
5
// yields [
//     "text",
//     "submit"
// ]
cy.get('input').attribute('type');

获取data-attribute属性值

1
2
<div data-attribute=" Extravagant  
  Eagle            "></div>

默认省去空格

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

省去空格–通默认一直

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

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

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

不省去空格

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