Cypress: Validating Count of Elements on the Page

Profile picture for user arilio666

In this article, we will see about validating the count of elements present on a page. For this example, we are going to do the following.

  1. Navigate to the programsbuzz site.
  2. Search 'Cypress' and click on the go.
  3. Validate count of articles written by 'arilio666'.

     Cypress: Validating Count of Elements on the Page

The search result page looks something like this.

       cy.visit('https://www.programsbuzz.com/')
       cy.get('.fas.fa-search').click()
      cy.get('#edit-keys').type('Cypress')
  
      cy.get('#edit-submit').click()
       
       cy.xpath("//div[@class='search-result__snippet-info']/p[2]")
       .find('>a:contains("arilio666")')
       .then(($value) => {
           length = $value.length
           expect($value).to.have.length(length);
           cy.log("*** length obtained *** " + length)
       })
  • After the search result page appears, we isolate the author part of the element, and with the help of find, we are giving arilio666 as input within contains.
     Cypress: Validating Count of Elements on the Page
  • Using then, we are validating the argument with length and expecting it to have the length it yields.
  • We can see that five counts of 'arilio666' are found on this page alone.
 Cypress: Validating Count of Elements on the Page
  • Cypress also logged the length to 5.

Conclusion:

This is how we can validate the count of elements by taking common elements and fetching their length.