Search code examples
javascriptdropdowncypresshtml-select

cypress how to verify all dropdown items without selecting any item


Below is my html for a dropdown control: enter image description here

I want to verify that drop down has following items: ["5","15","30","45"]

I have written following piece of code:

value=["5","15","30","45"]
cy.get(seelctor).invoke('val').should('deep.equal', value)

I do not want to select all of these items just want to verify that drop down has them. Also, My html does not has the value attribute. How do i assert based on text ??


Solution

  • The values between tags like <li>15</li> are accessed on individual element with .invoke('text').

    invoke('val') is for <input> and <textarea> elements.

    But if you select multiple elements, the texts will mash together

    cy.get('li')                  // multiple elements selected
      .invoke('text')             // joins all text together, result is "5153045"
      .should('eq', '5153045')    // passes
    

    In your case it's ok, but feels a little clumsy. In another scenario you can get additional white space between texts which makes it harder to compare.

    You can use jQuery to extract individual texts, and they can be trimmed to make a better match when extra white-space is present

    cy.get('li')                                            
      .then($els => Cypress.$.map($els, (el) => el.innerText.trim())) // uses jQuery .map()
      .should(values => {
        expect(values).to.deep.eq(["5","15","30","45"])
      })
    

    But if your dropdown items are fetched from an API, you should put as much of the calculation as possible inside the .should() callback, because Cypress retries until passing

    cy.get('li')                                            
      .should($els => {                                              // retries here
        const values = [...$els].map(el => el.innerText.trim())      // uses Array .map()
        expect(values).to.deep.eq(["5","15","30","45"])
      })