安装插件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
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
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' });