Saad Ahmed Khan
Saad Ahmed Khan

Reputation: 35

Return text from function cypress

I need to return extracted text in function. I'm extracting text but cannot return it to use in functions

    getAmounttxt() {
            cy.get('#product_price_1_1_0 > .price').invoke('text').as('ame')
            cy.get('@ame').then((ame) => {
                cy.log(ame)
            })

Upvotes: 0

Views: 1357

Answers (2)

K.A.Plilkington
K.A.Plilkington

Reputation: 171

Just use your alias as the returned value, it is there to help with asynchronous commands.

getAmounttxt() {
  cy.get('#product_price_1_1_0 > .price').invoke('text').as('ame')
}

// in test
getAmounttxt();
cy.get('@ame').then((ame) => {
  cy.log(ame)
})

Upvotes: 3

Mikhail Bolotov
Mikhail Bolotov

Reputation: 1112

Cypress commands are asynchronous and thus do not compute a value directly, so you can't return a value from a function using a cypress command.

What you can do is return a Chainable and obtain a value within a then callback:

    getAmounttxt() {
        return cy.get('#product_price_1_1_0 > .price').invoke('text')
    }
    
    it('test', () => {
       getAmounttxt().then(ame => {
          cy.log(ame)
       })
    })

Also, you can use an alias to transfer you values. Please look into alias wrapper approach if you want to have an alias represented as a real variable which can be passed through all your code.

Upvotes: 2

Related Questions