Cypress如何选择包含文本的选项

Arn*_*d P 6 cypress

在 Cypress 中,该select('option-text')命令仅在完全匹配时才有效。我如何告诉它选择包含文本的选项\xc2\xa0?

\n

小智 5

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

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


Arn*_*d P 0

到目前为止,我还没有在 api 中找到类似的内容,也没有在 github issues 中找到类似的内容。

所以我在我的项目中添加了一个自定义命令

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