![](/img/trans.png)
[英]How to validate a large response body contains expected values in Cypress test?
[英]cyoress test validate div tag ID contains value
在 HTML 頁面上有嵌套的 div 標簽。 div 標簽 ID = x 或標簽 ID = y。 在不同的 HTML 頁中。
<--! example 1 --> <body> <div> <div></div> <div id=Y></div> </div> </body> <--! example 2 --> <body> <div> <div></div> <div></div> <div> <div id=X></div> </div> </div> </body>
我們可以遍歷 DOM 中的所有div
,並使用 JQuery 命令,我們可以確定div
是否具有特定的 id。
cy.get('div').each(($div) => {
if ($div.attr('id') === 'x') {
// code to run if id = X
} else if ($div.attr('id') === 'y') {
// code to run if id = y
} else {
// code to run if neither
}
})
如果您最終遇到的情況不止兩三個,我可能會建議您使用 switch 語句而不是 if/else。
此外,上面的代碼將解決您的問題,但可能會比您擁有一個您知道有或沒有div#X
/ div#Y
元素的穩定 DOM 時性能低。 在這種情況下,我們必須遍歷每一個 div 元素。 如果我們確定div#X
存在,我們就可以執行cy.get('div#X')
並繼續測試。 您可以通過添加特定的data-cy
attr(盡管id
應該足夠了)來確保這一點,更重要的是通過將測試編寫為行列式和原子的。
Go 到cypress/support/commands.js
文件並寫入以下內容:
Cypress.Commands.add('runCode', (id) => {
cy.get('#' + id).then(() => {
if ($ele.attr('id') == 'X') {
//Write the code when the id is X
} else {
//Write the code when the id is Y
}
})
})
然后在你的測試中寫:
cy.runCode("X") //When id is X
cy.runCode("Y") //When id is Y
jQuery 允許多個選擇器。
假設存在一個或另一個 ID,
cy.get('div[id="X"], div[id="Y"]')
.then($el => {
if ($el.attr('id') === 'X') {
Xcode()
}
if ($el.attr('id') === 'Y') {
Ycode()
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.