As cypress documentation says
You cannot assign or work with the return values of any
Cypress command. Commands are enqueued and run asynchronously.
// this won't work the way you think it does
const button = cy.get('button')
const form = cy.get('form')
button.click()
For more information refer : variables-and-aliases
You have a few options. But you need to keep in mind the asynchronous nature of cypress
- Use alias (if you want to share the article variable in other tests ) so the code will look like this,
Example:
it("Test 1", () => {
cy.get('.inventory_item_price').invoke('text').as('article')
})
//Now you can use this.article in all the other test cases
//If you are using aliases remember Not to use arrow functions on hooks
it("Test 2", function(){
//this will log Backpack
cy.log(this.article)
})
- Use
.then
, As mentioned by @konekoya in the answer, Since cypress is asynchronous you need to use .then
to execute a task after a previous task is completed.
Example:
cy.get('.inventory_item_price').invoke('text').then(article=> {
//you can use articale variable as much as you want inside .then
//you can't use it outside
const value = articale ;
cy.log(article)
cy.log(value )
})
Note: to get inner Text you there are several methods. You can do the same thing using,
cy.get('.inventory_item_price').then(article => {
const value = articale.text() ;
cy.log(article.text())
cy.log(value)
})
cy.get('div').should('have.text', 'Backpack')
in case you try to assert on element’s text content – Balfour