'How to return string value with .wrap and cypress command feature
I have a code :
Cypress.Commands.add('getLabelText', (parentSelector: string, label: string) => {
var result: string= '';
cy.get(parentSelector).within(() => {
cy.get(`[aria-label="${label}"]`).then(el => {
result.replace(el.text(), '')
})
return cy.wrap(result)
})
})
I have tried many different ways to assign new value to string, this example is just one of those.
I want to return element text and use it like :
verifyText: () => {
cy.getLabelText(locator, expectedString).then(value => {
expect(value).to.eq(expectedString)
})
},
Cypress will return locatro insted of text:
expected '<div.v-data-table.summary-table.v-data-table--dense.v-data-table--fixed-height.theme--light>' to equal 'expectedString'
Any suggestion?
Solution 1:[1]
Make the cy.wrap() the last action in the chain. No need to return since you are accessing the last subject on the chain with .then(value =>
Cypress.Commands.add('getLabelText', (parentSelector, label) => {
let result = '';
cy.get(parentSelector).within(() => {
cy.get(`[aria-label="${label}"]`).then(el => {
result = el.text()
})
}).then(() => {
cy.wrap(result)
})
})
Solution 2:[2]
In order to return the value, you will have to return the entire chain.
Cypress.Commands.add('getLabelText', (parentSelector: string, label: string) => {
return cy.get(parentSelector).within(() => {
return cy.get(`[aria-label="${label}"]`).then(el => {
return el;
})
})
})
...
verifyText: () => {
cy.getLabelText(locator, expectedString).then(el => {
expect(el.text()).to.eq(expectedString)
})
}
Additionally, if your expectedString will always be the same for the function and the assertion using the result of the function, you can just assert in the function.
Cypress.Commands.add('getLabelText', (parentSelector: string, label: string) => {
cy.get(parentSelector).within(() => {
cy.get(`[aria-label="${label}"]`).then(el => {
expect(el.text()).to.eq(label);
})
})
})
...
verifyText: () => {
cy.getLabelText(locator, expectedString);
}
Solution 3:[3]
If the aria-label matchs the text content,
Cypress.Commands.add('getLabelText', (parentSelector: string, label: string) => {
const selector = `${parentSelector} [aria-label="${label}"]`;
cy.get(selector)
.invoke('text') // this text is returned
.should('eq', label)
})
})
cy.getLabelText(locator, expectedString)
.then(value => {
expect(value).to.eq(expectedString)
})
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 | Fody |
| Solution 2 | agoff |
| Solution 3 | Vispo |
