I have the div with classname 'okrSelectorSelect__value-container' in DOM.
<div ><div>
This div is optional. I want to click on it and do some additional tests with block that appears after that IF IT EXIST. I'm trying this.
cy.get('.okrSelectorSelect__value-container').then(($higherObjectivePick) => {
if ($higherObjectivePick.length > 0) {
$higherObjectivePick.click();
}
});
But got this when block is not on the page
Here is my solution, but looks like there is much more beautiful ways to do that.
cy.get('body').then($body => {
if ($body.find('.okrSelectorSelect__value-container').length > 0) {
cy.get('.okrSelectorSelect__value-container').click();
cy.get('.okrSelectorSelect__option').eq(higherOrderObjectiveNumber).click();
}
});
CodePudding user response:
I usually do the same like you but it would be more pretty to create a custom command for it like this:
Cypress.Commands.add("clickIfExists",(containerId , ItemId)=>{
cy.get('body').then($body => {
if ($body.find(containerId).length > 0) {
cy.get(ItemId).click();
}
});
})
and by this way you can always call it like that if you would like to click on .okrSelectorSelect__option
:
cy.clickIfExists(".okrSelectorSelect__value-container",".okrSelectorSelect__option")
CodePudding user response:
You could use jquery operators to check the existence of an element and wrap that function as below, adding to your support.js file:
Cypress.Commands.add("checkIfClassExists", (classToFind) => {
return Cypress.$(classToFind).length>0
})
Then in your tests:
if (cy.checkIfClassExists('.okrSelectorSelect__value-container')) {
//do something
} else {
//do nothing
}