Home > OS >  Cypress, get the numeric value of an attribute
Cypress, get the numeric value of an attribute

Time:11-25

To avoid going crazy again, is it possible to get the value of the htmlTemplateof this element?

 <rect x="303" y="28" height="53" width="10" htmlTemplate="foo: 115" ></rect>

I would like to get the number of that foo, so just the number 115

CodePudding user response:

If you just want to assert the value foo: 115 then you can do this.

cy.get('rect').invoke('attr', 'htmlTemplate').should('equal', 'foo: 115')

Now if you want to extract the number part, you can do something like this:

cy.get('rect')
  .invoke('attr', 'htmlTemplate')
  .then((val) => {
    cy.log(val.split(' ')[1]) //prints 115
    expect(val.split(' ')[1]).to.equal('115')
  })

If you have more than one rect and you want to access the first one you can use eq(0)

cy.get('rect').eq(0).invoke('attr', 'htmlTemplate').should('equal', 'foo: 115')

If you want to get the value of all the rects, you can use each(), something like:

cy.get('rect').each(($ele) => {
  cy.wrap($ele)
    .invoke('attr', 'htmlTemplate')
    .then((val) => {
      cy.log(val.split(' ')[1]) //prints value one by one
    })
})
  • Related