Home > Blockchain >  How to return string value with .wrap and cypress command feature
How to return string value with .wrap and cypress command feature

Time:04-16

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?

CodePudding user response:

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

CodePudding user response:

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