Creating a custom command can make your test more readable, encapsulate a group of commands that are repeated and need to be parameterized.
For your example testing the text of dropdown items, you can pass in the text and return the select so that chaining is possible
NOTES
In your code, .find().invoke("text")
returns all the item text in one string, so I added .contains()
to select an individual item.
If you're only interested in a partial match, the command chain can stop at .contain(text.trim())
Cypress.Commands.add('hasSelectedItemText',
{ prevSubject: true },
(subject, text) => {
cy.wrap(subject)
.find('span[class="ember-power-select-selected-item"]')
.contains(text.trim())
.invoke("text")
.should('eq', text.trim())
cy.wrap(subject) // returns the original select
}
)
cy.get(selector)
.hasSelectedItemText('one')
.hasSelectedItemText('two')
.hasSelectedItemText('three')
A more complicated example using the dual type command. Here the command can be parent or child, so the parameters have different meanings depending on usage
Cypress.Commands.add("dropdownItemText",
{ prevSubject: "optional" },
(subject, arg1, arg2) => {
if (subject) {
const text = arg1
cy.wrap(subject)
.find('span[class="ember-power-select-selected-item"]')
.contains(text.trim())
.invoke("text")
.should('eq', text.trim())
cy.wrap(subject) // returns the original select
} else {
const text = arg2
cy.get(arg1)
.find('span[class="ember-power-select-selected-item"]')
.contains(text.trim())
.invoke("text")
.should('eq', text.trim())
cy.get(arg1) // make select the returned "subject" for further chaining
}
}
)
cy.dropdownItemText(selector, 'one')
.dropdownItemText('two')
.dropdownItemText('three')