0

Hi I am new to Cypress and trying to automate this scenario -

I have a dropdown like this having duplicate values:

  <select name="cars" id="cars">
    <option value="volvo">Volvo</option>
    <option value="volvo">Volvo</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>

Now I want to select the second Volvo that appears on the list. Things I have tried:

cy.get('select#cars').select('Volvo') //This selects the first Volvo

Edit: Now Based on the selection above, a new element is displayed on the webpage and I am checking the inner text of that element -

cy.get('selector', {timeout: 8000}).should('have.text', some text)
4
  • How do you know you are selecting the first? They are identical. How does the app behaviour differ if the first or the second is selected by the user? Commented Jul 19, 2021 at 12:01
  • Based on the selection a certain other element is displayed. And I am then validating it using cy.get('selector', {timeout: 8000}).should('have.text', some text). Commented Jul 19, 2021 at 12:03
  • There must be something different that triggers the other element. Commented Jul 19, 2021 at 12:05
  • You can use indexing cy.get('select#cars').select('Volvo').eq(1) Commented Jul 19, 2021 at 12:06

1 Answer 1

1

Looking at the Cypress source code, the .select() command dispatches input and change events to the option chosen.

You can do the same, "manually" selecting

cy.get('option').eq(1).then($option => {

  const input = new Event('input', { bubbles: true, cancelable: false })
  $option.get(0).dispatchEvent(input)

  const change = document.createEvent('HTMLEvents')
  change.initEvent('change', true, false)
  $options.get(0).dispatchEvent(change)
})

Ref: cypress/packages/driver/src/cy/commands/actions /select.ts


Also this works

cy.get('option').eq(1)
  .trigger('input', { force: true })   
  .trigger('change', { force: true })  
  // force because select is not open so option isn't visible

While either way triggers events, it does not select the option.

This will do that,

cy.get('option').eq(1)
  .trigger('input', { force: true }) 
  .trigger('change', { force: true })
  .then($option => {
    cy.get('select').then($select => $select.val($option.val()))
  })
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is excellent! Can you add some links so we can learn?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.