Home > Mobile >  Cypress - getting values of element
Cypress - getting values of element

Time:08-05

I have the below two different HTML elements:

<h1 >Collectie</h1>

<span >4655</span>

I am able to get them using:

cy.get('.heading-1').should('have.class', 'heading-1 page-header-heading')
cy.get('.results').should('have.class', 'results')

But I need to extract the values in between, that is Collectie and 4655

I tried :

cy.get('.heading-1').should('have.value', 'Collectie')
cy.get('.results').should('have.value', '4655')

But getting the below errors:

 expected '<h1.heading-1.page-header-heading>' to have value 'Collectie', but the value was ''
 expected '<span.results>' to have value '4655', but the value was ''

How should I get those 2 values in Cypress and validate?

CodePudding user response:

You have to use have.text as you are asserting inner text.

cy.get('.heading-1').should('have.text', 'Collectie')
cy.get('.results').should('have.text', '4655')

For case 1, in case you want to use both the class names you can do this:

cy.get('.heading-1.page-header-heading').should('have.text', 'Collectie')

In case you want to check greater or less than, you can do like this:

cy.get('.results')
  .invoke('text')
  .then((text) =>  text)
  .should('be.gt', 4000) // greater than
cy.get('.results')
  .invoke('text')
  .then((text) =>  text)
  .should('be.gte', 4000) // greater than equal to
cy.get('.results')
  .invoke('text')
  .then((text) =>  text)
  .should('be.lt', 9000) // less than
cy.get('.results')
  .invoke('text')
  .then((text) =>  text)
  .should('be.lte', 9000) // less than equal to

CodePudding user response:

Besides using have.text, other thing you can do is using text() method within a promise combined with expect assertions. This way allows you to go further in your validation. Check bellow.

  cy.get('.heading-1').then(el => {
        let text = el.text()
        cy.log(`the expected text is: ${text}`)
        expect(text).equal('Collectie')
    })
  • Related