Dhamo
Dhamo

Reputation: 1251

How to create a custom select command to select by option value in cypress

For the following html,

             <select class="cell dropdown" data-test="Visibility-warn">
                <option value="">Select...</option>
                <!---->
                <option value="0"><!---->Good<!----></option>
                <!---->
                <option value="1"><!---->Moderate/Good<!----></option>
                <!---->
                <option value="2"><!---->Moderate<!----></option>
                <!---->
                <option value="3" selected=""><!---->Moderate/Poor<!----></option>
                <!---->
                <option value="4"><!---->Poor<!----></option>
                <!---->
            </select>

I have written the cypress code to select by value and not by text. As per docs, both select by text and select by value can be done in the same way.

        cy.get('[data-test="Visibility-warn"]')
                .should('be.enabled')
                .select('3')

which works fine.

But on the other hand, I am trying to create a custom command that does not work.

 cy.selectAndVerify('[data-test="Visibility-warn"]', weatherLimits.Visibility.warn, 'Moderate/Poor');
 //weatherLimits.Visibility.warn = gives the value 3

And in Commands:

Cypress.Commands.add('selectAndVerify', (selector, textToSelect, valueToVerify) => {
  cy.log(textToSelect)
  cy.get(selector)
    .should('be.enabled')
    .select(textToSelect)
  //.should('have.text', valueToVerify);
})

How can I possibly make the custom command work?

enter image description here

Upvotes: 1

Views: 504

Answers (2)

Alapan Das
Alapan Das

Reputation: 18626

What I think is happening is weatherLimits.Visibility.warn is passing a number that is 3 but cypress is expecting an string. so it should be .select(textToSelect + "")

Cypress.Commands.add(
  "selectAndVerify",
  (selector, textToSelect, valueToVerify) => {
    cy.log(textToSelect)
    cy.get(selector)
      .should("be.enabled")
      .select(textToSelect + "")
      .should("have.text", valueToVerify)
  }
)

Upvotes: 1

Dhamo
Dhamo

Reputation: 1251

Though @Alapan Das answer is already accepted, adding an answer that rightly does the "verify" part.

Cypress.Commands.add('selectAndVerify', (selector, textToSelect, valueToVerify) => {
  cy.get(selector)
    .should('be.enabled')
    .select(textToSelect + "")
  cy.get(selector).find('option:selected').should('have.text', valueToVerify)
})

and in test

cy.selectAndVerify('[data-test="Visibility-warn"]', weatherLimits.Visibility.warn, 'Moderate/Poor');

Upvotes: 0

Related Questions