1

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?

Fody
  • 23,754
  • 3
  • 20
  • 37
Darko Cvetković
  • 55
  • 1
  • 1
  • 9

3 Answers3

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)
  })
})
Fody
  • 23,754
  • 3
  • 20
  • 37
0

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);
  }
agoff
  • 5,818
  • 1
  • 7
  • 20
  • `.within() yields the same subject it was given from the previous command.` So I doubt if `return cy.get(parentSelector).within` could work here – Mikhail Bolotov Apr 15 '22 at 16:24
0

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)
  })
Visal
  • 537
  • 1
  • 6