to automate CRUD functionality I need to select the 2nd item from a static drop down and the html is like
<select name="segment[segment_contact_id]" id="segment_segment_contact_id">
<option value="73082">Rita Basu</option>
<option value="73349">researcher user</option>
</select>
So by using cypress I am using the hardcoded value and my code is like
const segmentUser2 = 'researcher user'
const userValue2 = 73349
cy.get('select#segment_segment_contact_id')
.select(segmentUser2)
.should('have.value', userValue2)
I need suggestion because I don't like to use the hardcoded value instead I would like to use always the 2nd item from the drop down dynamically.
You could do something like this
Cypress.Commands.add(
'selectNth',
{ prevSubject: 'element' },
(subject, pos) => {
cy.wrap(subject)
.children('option')
.eq(pos)
.then(e => {
cy.wrap(subject).select(e.val())
})
}
)
Usage
cy.get('[name=assignedTo]').selectNth(2)
Here is @ItsNotAndy's way without the custom command.
cy.get('select#segment_segment_contact_id')
.children('option').eq(1)
.then($option => {
cy.wrap($option).parent().select($option.val())
})
As a function
function selectNth(selector, pos) {
cy.get(selector)
.children('option').eq(pos)
.then($option => {
cy.wrap($option).parent().select($option.val())
})
}
selectNth('select#segment_segment_contact_id', 1)
Verifying from text displayed
cy.get('select#segment_segment_contact_id')
.find(':selected')
.contains('researcher user')
Verifying by selectedIndex
cy.get('select#segment_segment_contact_id')
.its('0.selectedIndex')
.should('eq', 1)
You can use this as well. Here first we are getting value of the second item in the list using the eq() command. Then once we have got the value, we are just simply passing that to select().
cy.get('select#segment_segment_contact_id option').eq(1).invoke('val')
.then((val) => {
cy.get('select#segment_segment_contact_id').select(val)
})
And if you want to just validate the value or text you can do:
cy.get('select#segment_segment_contact_id option')
.eq(1).should('have.value', 73349)
cy.get('select#segment_segment_contact_id option')
.eq(1).should('have.text', 'researcher user')