Scenario: Let’s imagine a scenario where we have a parent element with the ID my-element
, and we want to validate that each of its child elements contains a specific text. Below is the Cypress code to accomplish this task.
We start by defining a Cypress test using the ‘describe
‘ function. Inside the test, we have an ‘it
‘ block that represents our specific test case. The goal is to verify that each child element of ‘my-element
‘ contains the expected text.
In the above code, we first retrieve the parent element using cy.get('#my-element')
and assign it to the myElement
variable. Next, we define the expected text value we want to validate in the str
variable.
To handle scenarios where the parent element may have multiple child elements, we use the ‘its('length')
‘ method to retrieve the number of child elements.
Next, we log this count using cy.log()
for debugging purposes. This is purely optional and can be removed once the code works as expected.
Within the if
condition, we iterate through each child element using a for
loop. For each child element at index ‘i
‘, we select its children using ‘.children()
‘. Finally, we assert that each child element includes the expected text using ‘.should('include.text', str)
‘.
We discussed a practical example of using Cypress to verify child elements within a parent element. By leveraging Cypress’s powerful assertions and selector methods, we can easily validate that each child element contains the expected text.
Remember to adapt the code to your specific use case, such as updating the selector or modifying the expected text. Hope this helps!
Happy testing with Cypress!