![](/img/trans.png)
[英]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.