skip to Main Content

I am writing automated test case with Cypress – I need to loop through all children of the element and verify its data. The problem is that all the children are object with tags and href value attribute except for the first one. The first one is wrapped into a span creating the following hierarchy: parent -> span -> a with href value.

How to organise a loop? I am a new to Cypress and didn’t find anything similar to my issue.

I tried to remove the span element but it is removed with a child inside

2

Answers


  1. If I understand you correctly, here is what can help you.

    First, you define whether a current child is a span, if it is you are looking for its child inside a span element and working with found . If it is not a span, do the logic you need:

        cy.wrap(option)
          .children()
          .each(($child, index) => {
            if ($child.is('span')) {
             // Get an <a> element inside <span>
              const linkedinLink = $child.find('a');
              // Do any other logic
              return;
            } else if ($child.is('a')) {
              //Process all children except for the first one
              cy.wrap($child).should('have.attr', 'href', value);
              // Do any other logic
            } else {
              cy.log('Unexpected element type:', $child.prop('tagName'));
            }
          });
      };
    
    Login or Signup to reply.
  2. If you switch from .children() to .find() the query will return any child or grandchild and skip the span that is different for the first item.

    The .find() command looks any number of levels down the HTML tree, whereas
    .children() only takes the first level descendants.

    The result is a lot simpler, no need to do any if() else() construct and you can focus on verifying the data.

    cy.get(parent)
      .find('a')    // pick up parent->a as well as parent->span->a
      .each($a => {
        // ...verify its data
      })
    

    By the way – I tried to remove the span element – generally you don’t want to alter the page during a test, because there might be side effects to doing so that make your test different to the user experience.

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