I am trying to retrieve the string for the number of google searches in order to use it with a cypress test.
Google search results
This is the code I am trying to use to get it.
It retrieves null.
let text = cy.get('#result-stats').innerText
cy.log(text)
I have also tried with several other methods, like innerHtml or textContent.
I have tried getting the whole div, invoking the text, invoking the val, getting the children…
Nothing works…
What I want to get is the string "About 8.200.000.000.000 results". At this point I don’t care if the HTML syntax is present or not, I just want the number.
2
Answers
Cypress commands will yield their results wrapped in a
Chainable
, so trying to set a variable equal tocy.get().innerText
won’t work –cy.get()
does not yield a variable withinnerText
. Instead, you can use closures to set the value of yourtext
variable.Now, you might be looking at that and think "oh, I can just use
cy.get().invoke('text')
. But, again, that would yield aChainable<String>
variable, and not aString
variable.There are additional strategies to use for getting the text value of an element on the screen, depending on your use case. The above works for the method you outlined in the original question, but may not work in a more elaborate use case.
You will need to adjust the timeout of the
cy.get('#result-stats')
to get the element from the page.After that, it’s a matter of parsing the element text to a number.
I recommend using regex
/About (.+) results/
where(.+)
represents the number portion, and[1]
at the end gives you that as the output.cy.log()
inside the callback is asynchronous, so you should use the synchronous versionCypress.log()
.Result: