This element sometimes will be visible and sometimes won't. I want to cheek if it's visible in test, and if it's visible I want to click on it.
The thing is that I don't know if the element will be appear in the test.
It appears in some cases, and sometimes not, and the problem is that when I'm searching for it and it isn't visible, the test fails.
I tried try/catch and it didn't work.
I also tried if (cy.get('.text-center modal-header button[class="close"]').visible)
cy.get('button[class="close"]').click();
Get the parent element and look for your desired element in the .then with find.
eg (not tested the code, just to get the idea)
cy.get('#parent').then($element => {
if ($element.find('#desiredElement')) {
....
}
});
Hi @KWorke,
since Cypress use the jQuery syntax for working with the DOM elements I would suggest you to try the following:
cy.get('.text-center modal-header button[class="close"]')
.then($button => {
if ($button.is(':visible')) {
cy.get('.text-center modal-header button[class="close"]').click()
})
})
Please check the Conditional Testing Section for more information
Btw, I tried to execute click() on the $button element directly and it didn't work out (see my previous comment). So ended up with calling cy.get() within then().
Can someone please double check if it is something worth opening a separate issue for?
@KWorke you are trying to do conditional testing, which is part of our main guides, and both @Konstruktour and @vitaliysobur are pointing you down the right track. However, this is almost always an anti-pattern and you are likely going to be digging yourself into a hole because you generally cannot rely on the DOM if it's unstable.
@vitaliysobur I don't see anything wrong here regarding needing to open a second issue.
Calling .click() on a jquery element does just that - it calls .click() on the jquery element, which is implemented by jquery - just like the .is(...) method you're using.
Using cy.get(...).click() is part of the Cypress API which is why that works. FYI: this is why cy.wrap() exists.
if ($button.is(':visible')) {
cy.wrap($button).click()
}
Right, I forget that wrap is the thing! Thx @brian-mann
Most helpful comment
Hi @KWorke,
since Cypress use the jQuery syntax for working with the DOM elements I would suggest you to try the following:
Please check the Conditional Testing Section for more information