Cypress 元素定位

前言

今天我们介绍常见的元素定位方法,包括

cy.get()

// 方式1:id 选择器
cy.get('#query-btn').should('contain','Button')
// 方式2:标签 选择器
cy.get('button').should('contain','Button')
// 方式3:属性 选择器
cy.get('[id="query-btn"]').should('contain','Button')
// 方式4:标签+属性 选择器
cy.get('button[id="query-btn"]').should('contain','Button')
// 方式5:class 选择器
cy.get('.query-btn').should('contain','Button')
// 方式6:级联混合 选择器
cy.get('#querying .well>button').should('contain','Button')

//方式7::nth-child(n)
cy.get(tbody > tr:nth-child(1) > th')

cy.find()

该定位方法用来在 DOM 树中搜索已被定位到的元素的后代,并将匹配到的元素返回为一个新的 jQuery 对象【注意,不是返回元素对象】

it('测试find - 正确写法', () => {
cy.get("ul").find('#li1')
})
it('测试find - 错误写法', () => {
cy.find('#li1')
})

cy.contains()

该方法可用来获取包含指定文本的 DOM 元素

两种方式:

.contains(content)
.contains(selector, content)

cy.get('.query-list').contains('apples').should('have.class','first')
cy.get('#querying').contains('ul','apples').should('have.class','query-list')

重点:只会返回第一个匹配到的元素

posted @ 2022-07-02 19:43  keena_jiao  阅读(698)  评论(0编辑  收藏  举报