Cypress – Children
By Siddharth Murugan, Community Contributor - December 26, 2024
Cypress is a front-end testing tool built for the modern web. It provides solutions for end-to-end testing, component testing, accessibility testing, UI coverage, and more.
Cypress can test anything that runs in a browser. Behind Cypress is a Node server process. Cypress and the Node process constantly communicate, synchronize, and perform tasks on behalf of each other.
Access to both parts (front and back) allows you to respond to your application’s events in real-time while working outside the browser for tasks requiring higher privileges.
- What is Cypress-Children ()?
- Syntax of Cypress-Children ()
- Arguments with Cypress-Children ()
- Use cases of Cypress-Children ()
- How to use Cypress-Children ()
- Examples of using Cypress-Children ()
- Common errors while using Cypress-Children ()
- Best Practices for Cypress-Children ()
- Run Cypress tests on Real Browsers and Devices with BrowserStack
- Useful Resources for Cypress
What is Cypress-Children ()?
The method children() in Cypress is used to get the child elements present in the particular parent element.
For example, you may have a list element/table element and want to interact with its child elements.
Now, with the help of the children() method, you can interact with the other nested elements inside the parent element. This method gets the children of each DOM element within a set of DOM elements.
Syntax of Cypress-Children ()
The Cypress method children() has the syntax which looks as below,
cy.get(parentSelector).children(childSelector, options)
- The childSelector is optional, but the parentSelector should be present to extract its nested elements.
- The options are also not mandatory, and two options can be added.
- The children() method cannot be used independently (i.e., cy.children()) and should always be chained after cy.get() or cy.find().
- The children() method can indeed be chained with other methods like .eq(), .each(), .should(), etc.
- You can chain the children() method with any other relevant Cypress commands, but avoid chaining it in logically incorrect ways.
Also Read: How to Use cy.session()
Arguments with Cypress-Children ()
The children() method in Cypress has two options: log and timeout.
Option | Default value | Description |
---|---|---|
log | true | This displays the commands in the command log |
timeout | By default, it takes the timeout mentioned in the configuration file | Time to wait for the children() method elements. |
Use cases of Cypress-Children ()
Below are the key use cases of cypress childre:
- Validating the child element count: To verify the page’s structure, check if a parent element has the expected number of child elements.
cy.get(selector).children().should(‘have.length’,8)
- Iterate through the child element: When you need to perform actions on several child elements directly nested within a particular parent element, like selecting multiple items from a dropdown menu or clicking on multiple links within a navigation bar.
- Testing complex nested elements: When dealing with deeply nested elements, .children() can be combined with other DOM traversal methods like .eq() or .first() to pinpoint specific child elements within a complex hierarchy.
How to use Cypress-Children ()
Here is an example of how to take children from the parent element ul.
Consider an HTML page with the below tags,
<html></html> <body> <ul class="parent-element"> <li class="child-1">I'm a child element 1</li> <li class="child-2">I'm a child element 2</li> </ul> </body> </html>
To get the two listed elements inside the parent element, you should mention the following,
cy.get('.parent-element').children().should('have.length', 2)
With the above command, you should be able to get the two nested children elements and validate the length of the two elements present.
Examples of using Cypress-Children ()
So far, what you have seen is just a demonstration. Now, you will get hands-on experience using Cypress using the children() method.
Validating the child element count
- To validate the count of the child element, visit the BrowserStack demo website.
- Look for the navigation menu and validate the count as 3.
- Execute the code below.
describe('template spec', () => { it('test case', () => { //Visiting the BrowserStack demo website cy.visit('https://bstackdemo.com/') //Getting the three navigation bar elements and validating their count to be three // cy.get('.space-x-4').children().should('have.length',3) }) })
Iterate through the child element: There may be a scenario in which you should iterate through each element and find out its text.
Take a look at the code below to iterate through the navigation bar child element of the BrowserStack demo website.
describe('template spec', () => { it('test case', () => { cy.visit('https://bstackdemo.com/') //Iterating through child element and looking for the element with text as Orders cy.get('.space-x-4').children().each(($element) =>{ if($element.text() == "Orders") { cy.log("Element found") } }) }) })
Testing complex nested elements: When you get complex nested elements, you must click the element with index as 1.
For such scenarios also, you can combine with other methods and click the respective element like below code,
describe('template spec', () => { it('test case', () => { cy.visit('https://bstackdemo.com/') // clicking the first element from the list of the navigation menu cy.get('.space-x-4').children().eq(1).click() }) })
Common errors while using Cypress-Children ()
Below are some common errors while using Cypress children:
- Always ensure that the selector you are using to apply the children() method is correct. If you have any issues, use Cypress Selector Playground.
- The children () method can select only the direct children elements.
- Make sure to club the children() method with the get() method, as it cannot be directly used with the cy command.
Best Practices for Cypress-Children ()
Here are some best practices for using Cypress-Children:
- If the child element is visible after some time, use
cy.get().should('be.visible').children()
- Correctly chain children() with other Cypress commands like .each() to iterate through the child elements and perform actions on them.
- Not chaining children() correctly with other Cypress commands like .should() or .each() can lead to errors if you try to perform actions on the children without first selecting them properly.
Run Cypress tests on Real Browsers and Devices with BrowserStack
Testing web and mobile applications on real devices and browsers ensures a seamless user experience, platform compatibility, and reliable real-world performance. BrowserStack provides a robust platform with access to 3,500+ real devices and browsers for comprehensive testing.
- BrowserStack Automate lets you test native and hybrid apps on various mobile and tablet devices housed in secure data centers.
- Run Cypress tests across an extensive list of browsers and devices, with support for CI integration and Local Testing to streamline workflows.
- Testing on real devices and browsers helps ensure uniform application behavior and validates its performance and security under real user conditions.
Conclusion
The children() command in Cypress is a powerful tool for navigating and asserting the immediate child elements of a parent in the DOM. It allows you to directly filter and interact with specific child elements, providing better control and precision in your tests.
Use children() when you focus on immediate children, and remember to differentiate it from find() when deeper traversal is required. This ensures clarity and accuracy in your test scripts, enhancing overall test maintainability.
Useful Resources for Cypress
Understanding Cypress
- Cross Browser Testing with Cypress : Tutorial
- Run Cypress tests in parallel without Dashboard: Tutorial
- Handling Test Failures in Cypress A Comprehensive Guide
- Cypress Test Runner: Tutorial
- Handling Touch and Mouse events using Cypress
- Cypress Automation Tutorial
- CSS Selectors in Cypress
- Performance Testing with Cypress: A detailed Guide
- Cypress Best Practices for Test Automation
- Test React Native Apps with Cypress
- Cypress E2E Angular Testing: Advanced Tutorial
- Cypress Locators : How to find HTML elements
- Maximizing Web Security with Cypress: A Step-by-Step Guide
- Conditional Testing in Cypress: Tutorial
- Cypress Web Testing Framework: Getting Started
- Cypress Disable Test: How to use Skip and Only in Cypress
- What’s new in Cypress 10? How it will change your current testing requirements
Use Cases
- How to Record Cypress Tests? (Detailed Guide)
- How to run your first Visual Test with Cypress
- How to Fill and Submit Forms in Cypress
- How to Automate Localization Testing using Cypress
- How to run Cypress Tests in Chrome and Edge
- How to use Cypress App Actions?
- How to Run Cypress Tests for your Create-React-App Application
- How to Run Cypress Tests in Parallel
- How to handle Click Events in Cypress
- How to Test React using Cypress
- How to Perform Visual Testing for Components in Cypress
- How to run UI tests in Cypress
- How to test redirect with Cypress
- How to Perform Screenshot Testing in Cypress
- How to write Test Case in Cypress: (with testing example)
Tool Comparisons