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
votes
2 Answers
2
votes
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>;
}
}
<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