Home > database >  In Cypress 10, how can we check whether elements in drop-down are sorted alphabetically or numerical
In Cypress 10, how can we check whether elements in drop-down are sorted alphabetically or numerical

Time:06-10

enter image description here*I need to know all these listed data are sorted by XXXX digit number

CodePudding user response:

You can do something like this. Since I am not sure about the selector for the dropdown list item, I am adding just a placeholder selector, edit that with a valid selector

cy.get('selector').then(($elements) => {
  var strings = $elements.map(($el) => $el.text())
  cy.wrap(strings).should('equal', strings.sort())
})

CodePudding user response:

The steps to do this are

  1. get the option elements
  2. extract the text as an array
  3. slice off the number part
  4. compare members to sorted version
cy.get('.MuiAutocomplete-root').click()          // open the options list

cy.get('.MuiAutocomplete-option')                
  .should('have.length.gt', 1)                   // wait for loading options
  .then($options => {                            // 1. get the option elements

    const texts = [...$options].map(option => option.innerText)        // 2. extract the text as an array  
    const numbers = texts.map((text) =>  (text.split('-')[0].trim()))  // 3. slice off the number part

    expect(numbers).to.have.ordered.members([...numbers].sort())       // 4. compare members 
                                                                       // to sorted version
  })

Don't use .sort()

This gives you the wrong answer, for example

const strings =['b', 'a', 'c']
cy.wrap(strings).should('equal', strings.sort())  // passes, but it's not sorted!

because strings.sort() changes the original array and then compares it to itself, so will always pass even when original list is not sorted.

  • Related