testaway
testaway

Reputation: 350

Cypress returns undefined for invoked text

I am trying to pull the text from an element, to later make sure that it exists or doesn't exist after certain operations. Cypress pulls the text just fine but returns it as undefined during assertions and thus producing either a failing or a false positive result. Here's the code:

cy.get('.peeking-carousel__track')
            .children()
            .first()
            .find('.peeking-carousel__title')
            .invoke('text')
            .as('firstSlide')

        cy.get('@firstSlide')
            .then(firstSlide => {
                cy.log(firstSlide); //logs the text correctly
                cy.contains(firstSlide).should('be.visible'); //fails because can't locate it, even though it's displayed
               
                cy.get('.peeking-carousel')
                    .find('.icon-arrow-forward')
                    .should('have.css', 'cursor', 'pointer')
                    .click();
                cy.contains(firstSlide).should('not.exist'); //passes but refers to firstSlide as undefined
                
            })

I've been digging through similar problems on SO but couldn't find a solution that works for me.

Upvotes: 0

Views: 514

Answers (1)

Harry Trevaldwyn
Harry Trevaldwyn

Reputation: 176

I think the problem is with aliasing a text value. If you alias the element instead Cypress will retry querying the element.

Elements on a carousel are usually hidden rather than destroyed, so .should('not.exist') isn't the best test.

cy.get('.peeking-carousel__track')
  .children()
  .first()
  .as('firstSlide')
  .should('be.visible')

cy.get('.peeking-carousel')
  .find('.icon-arrow-forward')
  .should('have.css', 'cursor', 'pointer')
  .click()

cy.get('@firstSlide')
  .should('not.be.visible')

Upvotes: 6

Related Questions