Subtain Shah
Subtain Shah

Reputation: 49

How to iterate through each element of dropdown in cypress?

<div class="version-select">
  <label>Version</label>
    <select id="version-select" name="version">
        <option selected="selected" value="62e131f4c940e48cb85f56aa">10</option>
        <option value="62e13221c940e48cb85f6f12">09</option>
        <option value="62e1102946548a0eaecda47c">1.0.6</option>
    </select>
 </div>

I am to selecting each element one by one and then applying an assertion to find selected option text in Url. Every time when an option is selected from drop down,the selected version portal page is loaded in website and version is in URL.

    cy.get('#version-select').find('option').each(($opn)=>{
        cy.log($opn)
        let text = $opn.text()
        text= text.replace('.','_')
        cy.url().should("include",text)
    })

In first iteration assertion is passing but in second iteration t fails due to it is getting same previous URl.

Upvotes: 1

Views: 1968

Answers (1)

Fody
Fody

Reputation: 32044

I think you missed out the select step, which triggers the page navigation.

Try this:

cy.get('#version-select')
  .find('option').each(($opn)=>{
     const optionText = $opn.text()
     const urlText = optionText.replace('.','_')

     cy.get('#version-select')
       .select(optionText)                 // select the option

     cy.url().should("include", urlText)
  })

IMO it would be better to not rely on .each().

This is what I would try

const versions = ['10', '09', '1.0.6'] 

versions.forEach(version => {
  cy.get('#version-select').select(version)
  cy.url().should("include", version.replace('.','_')) 
})

Also since the page is changing you might need to increase timeout on the URL check if transition is slow.

In that case, use cy.location() instead

const versions = ['10', '09', '1.0.6'] 

versions.forEach(version => {
  cy.get('#version-select').select(version)
  cy.location('href', {timeout:10000})
    .should("include", version.replace('.','_')) 
})

Upvotes: 2

Related Questions