Child commands in Cypress - Build an Automation Script
describe('Child commands test', () => { beforeEach(() => { cy.visit('http://localhost:3000/items'); }); it('should verify child elements inside #item-list', () => { cy.get('#item-list') .children('.item') .should('have.length', 5) .first() .should('contain.text', 'Item 1'); cy.get('#item-list') .children('.item') .last() .should('contain.text', 'Item 5'); }); });
The test starts by visiting the target URL in the beforeEach hook to ensure a fresh page load before each test.
We use cy.get('#item-list') to select the container by its id, which is a reliable and clear selector.
Then, .children('.item') fetches all direct child elements with the class item inside the container.
We assert the number of these child elements is exactly 5 using .should('have.length', 5).
Next, we check the first child element contains the text 'Item 1' using .first().should('contain.text', 'Item 1').
Similarly, we check the last child element contains the text 'Item 5' using .last().should('contain.text', 'Item 5').
This approach uses Cypress chaining and child commands properly, making the test clear, maintainable, and reliable.
Now add data-driven testing with 3 different containers each having different numbers of child items and verify their counts and first/last item texts.