Reputation: 3
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)
Upvotes: 0
Views: 817
Reputation:
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()))
})
Upvotes: 3