Verify button text inside a specific parent element using cy.find()
Preconditions (2)
✅ Expected Result: The button inside the container is found and its text is 'Submit'. The test passes.
describe('cy.find() within parent test', () => { it('should find button inside container and verify text', () => { cy.visit('https://example.com/testpage'); cy.get('#container') .find('button.submit-btn') .should('have.text', 'Submit'); }); });
This test script uses cy.visit() to open the page.
Then cy.get('#container') locates the parent container by its id.
Inside that container, .find('button.submit-btn') locates the button with the class submit-btn.
Finally, .should('have.text', 'Submit') asserts the button text is exactly 'Submit'.
This approach ensures we only search inside the specific parent, making the test more reliable and clear.
Now add data-driven testing with 3 different button texts inside different containers.
cy.find() in Cypress tests?cy.find() rolecy.find() is used to look for elements inside a previously selected parent element, narrowing the search.cy.get() searches the whole page, while cy.find() limits to children of a parent element.submit-btn inside a div with id form-container using cy.find()?cy.get('#form-container') to select the div with the given id.find() on the parent to locate the child button.find('button.submit-btn') on the parent to get the button inside it.<div id='list'>
<ul>
<li class='item'>Apple</li>
<li class='item'>Banana</li>
<li class='item'>Cherry</li>
</ul>
</div>cy.get('#list').find('li.item').its('length')cy.get('#list') selects the div containing the list.li elements with class 'item' inside the div.find('li.item') selects all three list items: Apple, Banana, Cherry..its('length') returns the number of matched elements, which is 3.cy.get('.container').find('.button').click().find('.button') returns nothing, causing the error.div.card contains a button.delete. How do you click the delete button only inside the second card using cy.find()?cy.get('div.card').eq(1) selects the second card (index 1)..find('button.delete') searches only inside the selected card..click() clicks the delete button inside the second card only.Pass the test and this pattern moves unknown