I am trying to retrieve the string for the number of google searches in order to use it with a cypress test.
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.
Cypress commands will yield their results wrapped in a Chainable
, so trying to set a variable equal to cy.get().innerText
won't work - cy.get()
does not yield a variable with innerText
. Instead, you can use closures to set the value of your text
variable.
let text = "";
cy.get('#result-stats')
.invoke('text') // grab the text directly
.then((value) => {
text = value // set the variable `text` equal to the yielded `value`
}).then(() => {
cy.log(text); // log text in a separate .then because of how cy.log enqueues
});
Now, you might be looking at that and think "oh, I can just use cy.get().invoke('text')
. But, again, that would yield a Chainable<String>
variable, and not a String
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.