[英]Check if specific element in array contains a certain String. Then delete the element
[英]Cypress how to check if an element contains a certain string
赛普拉斯如何检查一个元素是否包含某个字符串?
我使用自定义检查元素是否存在代码来检查是否可以找到该元素(一条错误消息)然后我想检查该元素是否包含某些文本? 或者我可以使用查询选择器的 java function 吗?
cy.validateIfElementExistsInDomAsBoolean('[data-testid=alert-content]').then(bool => { // checks error to file see how it works
if (bool) {
if(cy.contains('[data-testid=alert-content]', "Your basket has been updated. Please refresh the basket to continue.")){
console.log("refresh site")
}else{
console.log("different error")
}
}else{
cy.log("Checked for error no error found")
}
})
可能你可以让你的自定义命令返回文本或空字符串
Cypress.Commands.add('validateIfElementExistsInDomAsString', (selector) => {
const $element = Cypress.$(selector);
if ($element.length > 0) {
return $element.text()
} else {
return ""
}
})
cy.validateIfElementExistsInDomAsString('[data-testid=alert-content]')
.then(error => {
if (error === "") {
cy.log("Checked for error no error found")
return
}
if (error === "Your basket has been updated. Please refresh the basket to continue.") {
console.log("refresh site")
} else {
console.log("different error")
}
})
假设validateIfElementExistsInDomAsBoolean
正确返回 boolean 值 true 或 false,您可以执行如下操作:
cy.validateIfElementExistsInDomAsBoolean('[data-testid=alert-content]').then(
(bool) => {
// checks error to file see how it works
if (bool) {
cy.get('[data-testid=alert-content]')
.invoke('text')
.then((text) => {
if (
text ==
'Your basket has been updated. Please refresh the basket to continue.'
) {
cy.log('refresh site')
} else {
cy.log('different error')
}
})
} else {
cy.log('Checked for error no error found')
}
}
)
如果您必须进行部分字符串检查,您可以更换
if (text=='Your basket has been updated. Please refresh the basket to continue.')
和
if (text.toLowerCase().includes(
'Your basket has been updated. Please refresh the basket to continue.')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.