2

I try to code something that will check the alphabetical order of the options in a dropdown menu. So what I do is to loop through the dropdown menu and adding the values of the options into an array. Then I want to check if the values of the array are in alphabetical order. So far I have this code:

var optionsArray = []
cy.get('#filter1 option').each(($el, index) => {
    optionsArray[index] = $el.text()
})
expect(optionsArray).to.equal(optionsArray.sort())

HTML:

<select id="filter1" class="form-control abc">
<option value="" selected="selected">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option><!----></select>

The problem is it passes the test when it should not. The following appears in the console: expected [] to equal [] And the expect() command seems to run before any other command that should run before.

How can I sort the values in the array in alphabetical order and compare if the options are equal?

EDIT: This is the new code that works:

        var optionsArray = []
        var optionsArraySorted = []
        cy.get('#filter1 option').each(($el, index) => {
            optionsArray.push($el.text())
            optionsArraySorted.push($el.text())
        })
        .then(() => {
            expect(optionsArray).to.deep.equal(optionsArraySorted.sort())
        })
TA1-q
  • 33
  • 1
  • 6

1 Answers1

2

Because of the asynchronous nature of Cypress commands, you have to add .then() after .each() for that to work.

Try this

var optionsArray = []
cy.get('#filter1 option').each(($el, index) => {
    optionsArray[index] = $el.text()
})
.then(() => {
  expect(optionsArray).to.deep.equal(optionsArray.sort())  // note deep for arrays
})
Fody
  • 23,754
  • 3
  • 20
  • 37
  • Thank you for the explanation about adding `.then()`. I realized that `.sort()` also changes the array so it would compare it to itself - a false passing of the test :) So I changed the code a little bit. See the edit of my post above. – TA1-q Oct 05 '21 at 10:30