'Cypress how to select option containing text
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 ?
Solution 1:[1]
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()}`)
})
Solution 2:[2]
A slightly improved variant of Can Akgun user is as following (bonus adding as cypress command):
/**
* 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());
});
});
In this way we do not need global variables.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | herrbischoff |
| Solution 2 | LucianDex |
