【问题标题】:Cypress how to select option containing text赛普拉斯如何选择包含文本的选项
【发布时间】:2019-02-12 14:45:05
【问题描述】:

在赛普拉斯中,select('option-text') 命令仅在完全匹配时才有效。我如何告诉它选择一个包含文本的选项?

【问题讨论】:

  • 请问您为什么要选择仅包含文本的选项?告诉我们更多关于你的场景。谢谢楼下的回答
  • 当然。我有一个 <select> 选项,其中不仅包含事物的名称,还包含一些可选的详细信息。举一个随机的例子,它可以是与价格相关联的产品名称(以帮助选择)。在我正在编写的测试的上下文中,我可以通过编程轻松获取的唯一内容是名称,而不是价格。我们还要提一下,我可以依靠名称和选项之间存在的双射(无需价格来选择特定选项)。
  • 顺便说一句,如果这就是把你带到这里的原因,我已经接受了我自己的答案,很抱歉忘记了。

标签: cypress


【解决方案1】:

通过别名可以让它工作:

cy.get('select')
  .find('option')
  .contains('YOUR TEXT')
  .as('selectOption')
  .then( () => {
    cy.get('select')
      .select(`${this.selectOption.text()}`)
  })

【讨论】:

    【解决方案2】:

    到目前为止,我还没有在 api 中找到类似的东西,在 github 问题中也没有。

    所以我在我的项目中添加了custom command

    // cypress/support/commands.ts
    Cypress.Commands.add('selectContaining', {prevSubject: 'element'}, (subject, text, options) => {
      return cy.wrap(subject).contains('option', text, options).then(
        option => cy.get('select#report-selection').select(option.text().trim())
      );
    });
    
    // cypress/support/commands_type.ts
    declare namespace Cypress {
      interface Chainable<Subject = any> {
        requestApi(method: HttpMethod, url: string, body?: RequestBody): Chainable<Cypress.Response>;
        selectContaining(text: string | string[], options?: Partial<SelectOptions>): Chainable<Subject>;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2019-12-18
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多