typescriptstringautomated-testscypresscypress-custom-commands

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

  • 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)
      })
    })