Skip to content
Advertisement

Find element by HTML in Cypress

I’ve started implementing Cypress for some regression tests, and I’m trying to find a particular element in a list of elements. The elements are in this format:

<div class="navigationIcon">
    <input>
    <div>
        <img class="navigationImage" src="[image/path]">
        <div class="navigationText">[navigation text]</div>
    </div>
</div>

On a single page, there are several of these. I’d like to try and target a specific on by the [navigation text], but it is possible for them to have similar text. My main example is one with “Profiles” and a second one with “Membership Profiles”. So, doing cy.contains("Profiles") will give me the “Membership Profiles” element instead of “Profiles”.

Please keep in mind, this is used in a function, like this:

Cypress.Commands.add('goTo', (places) =>
{
    // Navigate to the places
});

Where “places” is an array of pages to navigate to. So, I don’t know the exact text I’m looking for in the function to say something like and !text === 'Membership Profiles'.

Does anyone know how I can grab the elements by the html content? This is the function I came up with:

Cypress.Commands.add('goTo', (places) =>
{
    for (let i = 0; i < places.length; i++)
    {
        let place = places[i];
        let navLinks = Cypress.$('.navigationIcon').toArray();
        navLinks.some((link) =>
        {
            if (link.innerHTML.includes(`>${place.name}</div>`))
            {
                cy.wrap(link).click();
                return true;
            }
        });
    }
});

but this is moving onto the next outer for loop iteration too fast and the second time through the navLinks variable pulls the same elements from the previous iteration.

Does Cypress have something built in to let me search by HTML? I’ve been looking around the documentation, but I can’t find anything.

Advertisement

Answer

I came up with this, I haven’t tested it but I believe it will do what you’re after.

Cypress.Commands.add('goTo', place => {
  cy.get("div.navigationIcon > div > div").then($navs => {
    var $desiredNav = $navs.find($nav => {
      return $nav.text() == place;
    });

    cy.wrap($desiredNav).click();
});

To make it work with your places array, I’d do this, or the for loop could be placed in your tests:

Cypress.Commands.add('goToPlaces', places => {
  for (let i = 0; i < places.length; i++)
  {
    cy.goTo(places[i]);
  }
});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement