Reputation: 254
Hello I'm trying to run the following code but somehow it does not work. The same code will work if I simply separate the IF statement in 2 and nest it. My intention is to select only one element from the dropdown list but buy using includes, I'm getting 2 results; that is why I was trying to add an extra condition to it.
cy.get("#autocomplete").type("ne");
cy.get(".ui-menu-item").each(($el) => {
if ($el.text().includes("Netherlands" && $el.text().length === 11)) {
cy.wrap($el).click();
}
Do you happen to know why that is? is there a better way of doing this? thank you
Upvotes: 1
Views: 3526
Reputation: 1468
I had a somewhat similar issue where I want to select an item in a custom select component (so not a native select
element).
I used a derivation of the most upvoted answer to achieve this:
cy.get('my-component .ng-dropdown-panel .ng-option')
.filter((_, el) => {
return el.querySelector('span.badge-location')?.textContent === locationName
&& el.querySelector('span.platform-name')?.textContent === platformName;
})
.should('have.length', 1)
.click();
The code loops through all possible option elements and finds the one I'm looking for and clicks on that one.
Upvotes: 0
Reputation:
You could do it with a .filter()
with a function parameter.
This variation is not currently in the Cypress docs, but they are using jQuery under the hood so refer here jQuery docs, filter(function).
Note the function receives the raw DOM element so use innerText
instead of jQuery .text()
.
You can add multiple criteria, but with ===
it checks for an exact match and the length check isn't needed.
cy.get("#autocomplete").type("ne");
cy.get('.ui-menu-item') // all items
.filter((index, el) => el.innerText === "Netherlands") // precise match
.eq(0) // take the first
.click(); // select it
Upvotes: 3
Reputation: 18576
There is a )
missing after the text Netherlands, you have to add that and there is an extra bracket )
added after 11, you have to remove that. So, your code should be:
cy.get("#autocomplete").type("ne");
cy.get(".ui-menu-item").each(($el) => {
if ($el.text().includes("Netherlands") && $el.text().length === 11) {
cy.wrap($el).click();
}
Upvotes: 0