0
0
Cypresstesting~15 mins

cy.find() within parent in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify button text inside a specific parent element using cy.find()
Preconditions (2)
Step 1: Visit the web page URL 'https://example.com/testpage'.
Step 2: Locate the container element by id 'container'.
Step 3: Within the container, find the button element with class 'submit-btn'.
Step 4: Verify that the button text is exactly 'Submit'.
✅ Expected Result: The button inside the container is found and its text is 'Submit'. The test passes.
Automation Requirements - Cypress
Assertions Needed:
Verify the button text inside the container is 'Submit'.
Best Practices:
Use cy.get() to locate the parent container by id.
Use cy.find() to locate the child button within the parent container.
Use should('have.text', 'Submit') for assertion.
Avoid using hardcoded waits; rely on Cypress automatic waiting.
Use clear and descriptive selectors.
Automated Solution
Cypress
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.

Common Mistakes - 3 Pitfalls
Using cy.get() instead of cy.find() to locate child inside parent
Using contains() to find button text without scoping to parent
Hardcoding waits like cy.wait(500) before finding elements
Bonus Challenge

Now add data-driven testing with 3 different button texts inside different containers.

Show Hint