赛普拉斯如何 select 包含文本的选项

Cypress how to select option containing text

在 Cypress 中,select('option-text') 命令只有在完全匹配时才会起作用。我如何告诉它 select 一个 包含 文本的选项?

到目前为止,我在 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>;
  }
}

通过别名你可以让它工作:

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

Can Akgun 用户的一个稍微改进的变体如下(作为 cypress 命令添加的奖金):

 /**
 * Select an option containing part of string in its text body
 * {String} elementSelector
 * {String} optionTextPart
 */
 Cypress.Commands.add('selectOptionContaining', (elementSelector, optionTextPart) => {
    cy.get(elementSelector)
    .find('option')
    .contains(optionTextPart)
    .then($option => {
        cy.get(elementSelector).select($option.text());
    });
});

这样就不需要全局变量了