0
0
Cypresstesting~15 mins

Parent commands in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify parent command usage to find child element
Preconditions (2)
Step 1: Open the web page at 'http://localhost:3000/items'
Step 2: Locate the <ul> element with id 'item-list'
Step 3: Use the parent command to find the <li> child elements inside the <ul>
Step 4: Verify that the first <li> element contains the text 'Item 1'
✅ Expected Result: The first <li> child element inside the <ul> with id 'item-list' contains the text 'Item 1'
Automation Requirements - Cypress
Assertions Needed:
Verify the <ul> element with id 'item-list' exists
Verify the first <li> child element inside the <ul> contains text 'Item 1'
Best Practices:
Use cy.get() with id selector for parent element
Use .children() or .find() to locate child elements
Use .first() to select the first child
Use .should() for assertions
Avoid hardcoding XPath selectors
Use explicit waits implicitly handled by Cypress commands
Automated Solution
Cypress
describe('Parent commands test', () => {
  it('should find first child li using parent commands', () => {
    cy.visit('http://localhost:3000/items');
    cy.get('#item-list')
      .children('li')
      .first()
      .should('contain.text', 'Item 1');
  });
});

This test opens the page at the given URL.

It uses cy.get('#item-list') to select the parent <ul> element by its id.

Then it uses .children('li') to get all direct <li> child elements.

.first() selects the first <li> child.

Finally, .should('contain.text', 'Item 1') asserts that this first child contains the expected text.

This approach follows Cypress best practices by using clear selectors and built-in commands for parent-child relationships.

Common Mistakes - 3 Pitfalls
Using cy.get() with a complex XPath to find child elements
{'mistake': 'Using .parent() instead of .children() to find child elements', 'why_bad': ".parent() moves up the DOM tree, not down to children, so it won't find child elements.", 'correct_approach': 'Use .children() or .find() to locate child elements from a parent.'}
{'mistake': 'Not waiting for the page to load before selecting elements', 'why_bad': 'Elements may not be present yet, causing test failures.', 'correct_approach': "Use cy.visit() and rely on Cypress's automatic waiting before querying elements."}
Bonus Challenge

Now add data-driven testing to verify the first child text for three different lists with ids 'item-list1', 'item-list2', and 'item-list3' each having different expected first item texts.

Show Hint