最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cypress: Check if Select Option Exists - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

I 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      
    }
  })
发布评论

评论列表(0)

  1. 暂无评论