Search code examples
javascripttestingautomationcypress

how to find all elements and matching partial text in cypress and Javascript


I have this DOM Structure

<a href=***engineer-jobs-in-london" data-id="49744949" title="Engineer" class="" data-gtm="sponsored_job_click" data-gtm-value="49744949">
                        Engineer
                    </a>


<a href="***engineer-jobs-in-london" data-id="49948533" title="Engineer" class="" data-gtm="sponsored_job_click" data-gtm-value="49948533">
                        Engineer
                    </a>

<a href="***engineer-jobs-in-london" data-id="49948533" title="Engineer" class="gtmJobTitleClickResponsive" data-gtm="job_click" data-gtm-value="49948533">
                        Engineer
                    </a>

<a href="****engineer-jobs-in-london" data-id="49948533" title="Engineer" class="gtmJobTitleClickResponsive" data-gtm="job_click" data-gtm-value="49948533">
                        Engineer
                    </a>

<a href="***engineer-jobs-in-london" data-id="49744949" title="Engineer" class="gtmJobTitleClickResponsive" data-gtm="job_click" data-gtm-value="49744949">
                        Engineer
                    </a>

<a href="***engineer-jobs-in-london" data-id="49744949" title="Engineer" class="gtmJobTitleClickResponsive" data-gtm="job_click" data-gtm-value="49744949">
                        Engineer
                    </a>

<a href="****engineer-jobs-in-london" data-id="49712390" title="BI Engineer" class="gtmJobTitleClickResponsive" data-gtm="job_click" data-gtm-value="49712390">
                        BI Engineer
                    </a>

This is not whole DOM structure, only the relevant part. There are more than 100 anchors tags with similar pattern.

My problem is, I need make sure Engineer text should appear more than 5 times in web page.

Also London should be present more than 5 times in the href tag.

I tried this:

 cy.contains('Engineer').should('be.greaterThan', 5)

but it always retyring 1 and it throwing Assertion error.

Where is my logic going wrong and what is the correct way implement this logic.


Solution

  • You will need to use another method, since cy.contains() only returns the first element (so count is always 1 with cy.contains()).

    Try this instead, it does the same thing in a different way to get the actual count of <a> elements with "Engineer" text.

    cy.get('a:contains(Engineer)')
      .its('length')
      .should('be.greaterThan', 5)