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())
})
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
})