2
votes

In Cypress, the select('option-text') command will only work if there is an exact match. How can I tell it to select an option that contains the text instead ?

2
Can I ask why you would want to select an option that just contains the text? Tell us more about your scenario. Thanks for the answer belowMaccurt
Sure. I have a <select> with options that contain not only the name of the thing, but also some optional details. To give a random example, it could be the name of a product, associated to its price (to help with the choice). In the context of the test I was writing, the only thing I could easily grab programmatically was the name, not the price. Let's also mention that I can rely on the bijection that exists between names and options (no need for the price to select a specific option).Arnaud P
BTW if that's what brought you here, I've accepted my own answer, sorry for having forgotten.Arnaud P

2 Answers

2
votes

Through aliasing you can make it work:

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

I haven't found anything like that in the api so far, nor in the github issues.

So I resorted to adding a custom command in my project:

// 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>;
  }
}