Cypress:检查选择选项是否存在

Fel*_*lli 3 javascript select cypress

我试图使用下面的代码检查我的选择中是否有一个选项,但它一直失败,有人可以提供一些帮助吗?

我的选择有大约 70 个名称,我正在尝试循环所有名称以查找特定名称。

        cy.get('[id="names"] option').each(($ele) => {
            expect($ele).to.have.text('Have This Name')
          })
Run Code Online (Sandbox Code Playgroud)

提前致谢,

keg*_*gne 7

我不会使用.each(),只有一个会通过,但任何其他都会失败。

.contains()如果您的文本足够具体(不在多个选项中),请使用

cy.contains('[id="names"] option', 'Have This Name')  // fails only if 
                                                      // no option has the text
Run Code Online (Sandbox Code Playgroud)

如果必须完全匹配,请过滤选项

cy.get('[id="names"] option')
  .filter((idx, el) => el.innerText === 'Have This Name')  // fails if filter 
                                                           // returns 0 items
Run Code Online (Sandbox Code Playgroud)

如果你想.each()有其他原因,这也可以

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')
  })
Run Code Online (Sandbox Code Playgroud)