I'm trying to check if there is an option in my select using the code below, but it keeps failing, can somenone give some help?
My Select have about 70 names and I'm trying to loop all them looking for the specific name.
cy.get('[id="names"] option').each(($ele) => {
expect($ele).to.have.text('Have This Name')
})
Thanks in advance,
I'm trying to check if there is an option in my select using the code below, but it keeps failing, can somenone give some help?
My Select have about 70 names and I'm trying to loop all them looking for the specific name.
cy.get('[id="names"] option').each(($ele) => {
expect($ele).to.have.text('Have This Name')
})
Thanks in advance,
Share Improve this question asked Feb 25, 2022 at 3:04 Fellipe RomanelliFellipe Romanelli 331 silver badge3 bronze badges2 Answers
Reset to default 7I would not use .each()
, only one will pass but any other will fail.
Use .contains()
if your text is specific enough (not in multiple options)
cy.contains('[id="names"] option', 'Have This Name') // fails only if
// no option has the text
If you have to match exactly, filter the options
cy.get('[id="names"] option')
.filter((idx, el) => el.innerText === 'Have This Name') // fails if filter
// returns 0 items
If you want .each()
for another reason, this will do
let found;
cy.get('[id="names"] option')
.each(($option) => {
if ($option.text() === 'Have This Name') {
found = $option
return false // return now, have found it
}
})
.then(() => { // after loop exit
expect(found).to.have.text('Have This Name')
})
You can handle the scenario like this-
cy.get('[id="names"] option').then(($ele) =>
{
if ($ele.text().includes('Have This Name'))
{
// do your statements
}
else
{
// do your statements
}
})