3

I'm new to and Cypress and I need to extract a dynamical part of a text from my application.

<body>
<div>Hello World greeting number 9123</div>
</body>

In this example I need to extract 9123 from the div, to use later in my tests. Any idea how I should do that?

Joshua
  • 3,055
  • 3
  • 22
  • 37
Aminimio
  • 43
  • 1
  • 4

2 Answers2

9

First you could try to get the full text from the div using 'invoke" method and the use RegExp and match in javascript to get the number from the text:

cy.get('div').invoke('text')
.then((text)=>{ 
    var fullText = text;
    var pattern = /[0-9]+/g;
    var number = fullText.match(pattern);
    console.log(number);
   })
soccerway
  • 10,371
  • 19
  • 67
  • 132
  • The returned number will be a string. What would be a better way to convert it into Integer, `parseInt` or does cypress provide something? – Saurav Mar 08 '21 at 10:39
1

I had to make some assumptions: 1. The number you want to retrieve is always at the end of the line 2. The sentence which holds the number is always divided by spaces. If those assumptions are correct this should work:

let divNumber = ''
    cy.get('div')
      .then(number => {
        divNumber = number
          .text()
          .split(' ')
          .pop()
        cy.get('div')
          .should('contain', divNumber)
Mr. J.
  • 3,499
  • 1
  • 11
  • 25