I am working with Cypress tests and currently facing an issue where I want to automate a click for an element from options, only if it is available. Here is the part of the code:
cy.get(Elements.jiraVulnerabilityTableTitle).should(
CyCondition.EXIST
);
cy.contains(Mocks.identifierColumn);
cy.get(Elements.securityContainerFilterButton).click();
cy.get(Elements.securityContainerOption).should(CyCondition.EXIST).click({force:true});
Here, securityContainerOption
is the button with which I am working on. I have a separate elements.js
file where I have set securityContainerOption
as #react-select-2-option-0-0
. But while running the tests, I have observed that sometimes #react-select-2-option-0-1
needs to be clicked and not #react-select-2-option-0-0
.
So, what I want is, after clicking securityContainerFilterButton
, I want to check if #react-select-2-option-0-1
is available, if yes, click on it. If it is not available, it should not fail, rather it should click #react-select-2-option-0-0
.
How do we add this conditional clicking of elements and not fail the test?
I tried the following changes:
cy.get('#react-select-2-option-0-1').then(($option) => {
if ($option.length > 0) {
cy.get('#react-select-2-option-0-1').click({force:true});
} else {
cy.get(Elements.securityContainerOption).should(CyCondition.EXIST).click({force:true});
}
});
But, in the above code, we do cy.get()
, and hence if the element is not found, it fails then and there itself.
Cypress does not fully support testing for one element or the other out of the box.
But provided the page is stable, you can just supply both selectors separated by a comma.
cy.get('#react-select-2-option-0-1, #react-select-2-option-0-0')
This will pass if one or the other selector is on the page. But as noted, the page must be stable before running the command because there is no retry in the query for your preferred element #react-select-2-option-0-1
.
Ideally you will want to chose a different way of selecting, perhaps by text insted of id.