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
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:
If you switch from
.children()
to.find()
the query will return any child or grandchild and skip thespan
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.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.