skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 version Cypress.log().

    cy.intercept({ resourceType: /xhr|fetch/ }, { log: false })
    
    cy.visit('https://google.com');
    
    cy.get('[title="Search"]')
      .type('Municipality of Laz Rozas de Madrid')
      .type('{enter}')
    
    cy.get('#result-stats', {timeout:20_000})
      .then((results) => {
        const text = results.text()
        const countAsText = text.match(/About (.+) results/)[1]
        const count = +countAsText.replaceAll(',', '')
        Cypress.log({displayName: 'Results count', message: count})
        return count
      })
      .should('be.gt', 1_000_000)
    

    Result:

    Cypress test log

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search