如何在赛普拉斯中获取按钮元素的名称
How to get name of the button element in Cypress
我需要创建一个条件,如果页面上有一个文本值为“Unblock”的按钮,它将提前通过 Cypress 被点击。单击部分和“if”条件我可以管理,我需要知道如何获取 javascript 来检测哪个按钮具有该文本值“Unblock”,谢谢!
cy.get(".scroller").eq(1).find("button").then(($scroller) => {
let test = $scroller //how to get the text value of the button?
console.log(test)
})
cy.wait(20000)
cy.contains("Unblock").click()
cy.wait(3000)
cy.contains("Close").click()
cy.contains("Back to main page").click()
1.You 可以使用 invoke('text') 获取按钮名称:
cy.get('.scroller')
.eq(1)
.find('button')
.invoke('text')
.then((text) => {
cy.log(text) //Logs button text
})
- 或者您也可以使用 Jquery
text()
来获取按钮名称:
cy.get('.scroller')
.eq(1)
.find('button')
.then(($scroller) => {
cy.log($scroller.text()) //Logs button text
})
因此在您的情况下,您可以像这样应用 if-else:
cy.get('.scroller')
.eq(1)
.find('button')
.then(($scroller) => {
if ($scroller.text().trim() == 'Unblock') {
//Do Something
} else {
//Do Something
}
})
您可以使用 cy.contains()
,因为它只有 returns 带有所需文本的一个按钮。
cy.contains("button", "Unblock")
.then(($scrollerButton) => {
console.log($scrollerButton.text())
})
我需要创建一个条件,如果页面上有一个文本值为“Unblock”的按钮,它将提前通过 Cypress 被点击。单击部分和“if”条件我可以管理,我需要知道如何获取 javascript 来检测哪个按钮具有该文本值“Unblock”,谢谢!
cy.get(".scroller").eq(1).find("button").then(($scroller) => {
let test = $scroller //how to get the text value of the button?
console.log(test)
})
cy.wait(20000)
cy.contains("Unblock").click()
cy.wait(3000)
cy.contains("Close").click()
cy.contains("Back to main page").click()
1.You 可以使用 invoke('text') 获取按钮名称:
cy.get('.scroller')
.eq(1)
.find('button')
.invoke('text')
.then((text) => {
cy.log(text) //Logs button text
})
- 或者您也可以使用 Jquery
text()
来获取按钮名称:
cy.get('.scroller')
.eq(1)
.find('button')
.then(($scroller) => {
cy.log($scroller.text()) //Logs button text
})
因此在您的情况下,您可以像这样应用 if-else:
cy.get('.scroller')
.eq(1)
.find('button')
.then(($scroller) => {
if ($scroller.text().trim() == 'Unblock') {
//Do Something
} else {
//Do Something
}
})
您可以使用 cy.contains()
,因为它只有 returns 带有所需文本的一个按钮。
cy.contains("button", "Unblock")
.then(($scrollerButton) => {
console.log($scrollerButton.text())
})