'cyoress test validate div tag ID contains value
On the HTML page nested div tags are there. And either div tag ID = x or tag ID =y. in different HTML pages.
<--! 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>
Solution 1:[1]
We can iterate through all divs in your DOM, and using JQuery commands, we can determine if the div has a certain 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
}
})
If you end up with more than just two or three cases, I'd probably recommend using a switch statement instead of if/else.
Additionally, the above code will solve your problem, but will probably be less performant than if you were to have a stable DOM that you knew either did or did not have the div#X/div#Y element. In this case, we have to traverse every single div element. If we knew for certain that div#X existed, we could just do cy.get('div#X') and get on with the tests. You could sure this up by adding a specific data-cy attr (although id should be sufficient) and more importantly by writing your tests to be determinant and atomic.
Solution 2:[2]
Go to cypress/support/commands.js file and write the following:
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
}
})
})
Then in your test write:
cy.runCode("X") //When id is X
cy.runCode("Y") //When id is Y
Solution 3:[3]
jQuery allows multiple selectors.
Presuming either one or other ID exists,
cy.get('div[id="X"], div[id="Y"]')
.then($el => {
if ($el.attr('id') === 'X') {
Xcode()
}
if ($el.attr('id') === 'Y') {
Ycode()
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | agoff |
| Solution 2 | Alapan Das |
| Solution 3 | Fody |
