55s25
55s25

Reputation: 11

Dynamic dropdown doesn't get selected the second time using cypress

I am new to cypress and trying to select a dropdown value from a dynamic list. The below snippet of code works fine for the selection of dropdown first time. It doesn't work for the second time. can you suggest, what is the problem with this code?

Cypress.Commands.add("selectValue", (valuetoSelect) => {

    cy.get(locators.selectDropdown).click()
    .then(() => {
        cy.get(locators.selectDropdown).type(valuetoSelect).wait(500)
            .get(locators.selectoption).each(($els) => {
               
                if ($els.text().trim() == "valuetoSelect") {
                    cy.wait(500);
                    cy.wrap($els).click();
                }
            })
    })
})

Upvotes: 0

Views: 374

Answers (1)

TesterDick
TesterDick

Reputation: 10550

Looks like you have a typo,

if ($els.text().trim() == "valuetoSelect") {

should be

if ($els.text().trim() === valuetoSelect) {

The shortest code for this is

Cypress.Commands.add("selectValue", (valuetoSelect) => {

  cy.get(locators.selectDropdown).click()            // open dropdown
  cy.contains(locators.selectoption, valuetoSelect)  // select option with valuetoSelect
    .click()
})

Upvotes: 1

Related Questions