Reputation: 43
cy.xpath('some xpath').then(($btn)=>{const text = $btn.text()})
I am currently using like this but i can use the text only inside .then() so i have problem of calling it outside . Please tell me how to get the text and store in a variable. e.g. var text= cy.xpath('some xpath') like this so that i can use it anywhere in inside the code.
Upvotes: 1
Views: 1933
Reputation:
Please be aware that all alias are cleared between tests.
This means if you do this
it('checks some xpath', () => {
cy.xpath('some xpath')
.then(($btn) => { return $btn.text()})
.as('myvar')
})
it('uses myvar', () => {
cy.get('@myvar').then((myvar) => {
const newvar = myvar + '2' // FAILS - "alias myvar has not been declared
})
})
Some better ways
Use alias from this
scope
it('checks some xpath', () => {
cy.xpath('some xpath')
.then(($btn) => { return $btn.text()})
.as('myvar')
})
it('uses myvar', function() { // note "function"
const newvar = this.myvar + '2' // this.myvar is set by alias but NOT cleared
})
Use "back-flip" variable
let myvar;
it('checks some xpath', () => {
cy.xpath('some xpath')
.then(($btn) => { return $btn.text()})
})
it('uses myvar', () => { // arrow function is ok
const newvar = myvar + '2' // myvar is global to both tests
})
Upvotes: 0
Reputation: 18586
You can use an alias using as
(cypress docs) to store your innerText.
cy.xpath('some xpath').invoke('text').as('text')
Now later if you want to use it you can use it like:
cy.get('@text').then((text) => {
//Do something with text
})
Upvotes: 2