Open In App

Cypress - parentsUntil() Method

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cypress is a very handy end-to-end testing framework that allows developers to test web applications using very simple tools. One of its DOM traversal methods which deserves a mention is the parentsUntil() method. It can help traverse to all the ancestors of a child element up to a given adult as the name suggests. This method comes in handy especially when you have nested structures to deal with and complex DOM trees to traverse. In this article, we are going to examine the parentsUntil() method, its usage, list of parameters, its syntax and even illustrate with some practical examples of effectiveness.

Usages of Cypress - parentsUntil() Method

The parentsUntil() method in Cypress is used to select all ancestor elements of a target element, starting from the selected element and continuing up the DOM tree until a specified parent (ancestor) is reached. Unlike the parents() method, which selects all ancestors, parentsUntil() allows you to control how far up the DOM you want to traverse by specifying a stopping point.

Key use cases of the parentsUntil() method include:

  • For selecting ancestors it traverses the DOM while excluding a specific stopping point.
  • Handling nested elements and complex hierarchies while interacting with multiple parent elements.
  • Simplifying traversal when you're interested in the ancestors between two elements, rather than all parents.

Syntax

The syntax for `parentsUntil()` method in Cypress is:

cy.get(selector).parentsUntil(stopSelector)
cy.get(selector).parentsUntil(stopSelector, filterSelector)
  • selector: The CSS selector used to select the element from which you want to start the traversal.
  • stopSelector: The selector for the ancestor element that acts as a stopping point. Cypress will stop the traversal when this ancestor is reached.
  • filterSelector: This ia an optional CSS selector to further filter the ancestors that are selected during the traversal of the DOM.

Arguments

  • selector: The CSS selector string for the element to start traversing from.
  • stopSelector: The CSS selector string that specifies the stopping point for the ancestor traversal. Ancestors up to but not including this element will be selected.
  • filterSelector: (Optional) A CSS selector string used to filter the ancestors being selected.

Examples

Here's the application code that we will be using as a sample for performing parentsUntil() method operations.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bookstore Customer Details</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: auto;
            background: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            color: #333;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        table,
        th,
        td {
            border: 1px solid #ddd;
        }

        th,
        td {
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        form {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 20px;
        }

        form input,
        form button {
            padding: 10px;
            font-size: 16px;
            flex: 1 1 100%;
        }

        form button {
            background-color: #5cb85c;
            color: #fff;
            border: none;
            cursor: pointer;
        }

        form button:hover {
            background-color: #4cae4c;
        }
    </style>
</head>

<body>
    <!-- file name - index.html  -->
    <div class="container">
        <h1 class="heading">Customer Details</h1>
        <table id="customerTable">
            <thead>
                <tr>
                    <th>Customer Name</th>
                    <th>Customer ID</th>
                    <th>Book Purchased</th>
                    <th>Quantity</th>
                    <th>Cost</th>
                </tr>
            </thead>
            <tbody>
                <!-- Rows will be added here by JavaScript -->
                <tr>
                    <td>John Doe</td>
                    <td>1001</td>
                    <td>The Great Gatsby</td>
                    <td>1</td>
                    <td>315.99</td>
                </tr>
                <tr>
                    <td>Jane Smith</td>
                    <td>1002</td>
                    <td>1984</td>
                    <td>2</td>
                    <td>629.98</td>
                </tr>
                <tr>
                    <td>Sam Brown</td>
                    <td>0903</td>
                    <td>To Kill a Mockingbird</td>
                    <td>1</td>
                    <td>512.99</td>
                </tr>
                <tr>
                    <td>Emily White</td>
                    <td>2004</td>
                    <td>The Catcher in the Rye</td>
                    <td>1</td>
                    <td>110.99</td>
                </tr>
            </tbody>
        </table>
        <div class="container1">
        <form id="customerForm" class="cus_form">
            <input type="text" class="form" id="customerName" placeholder="Customer Name" required>
            <input type="text" class="form"  id="customerID" placeholder="Customer ID" required>
            <input type="text" class="form"  id="bookPurchased" placeholder="Book Purchased" required>
            <input type="number" class="form"  id="quantity" placeholder="Quantity" required>
            <input type="number" class="form"  id="cost" placeholder="Cost" required>
            <button type="submit" class="form btn-submit" id="submit-new-row">Add Customer</button>
        </form>
        </div>
    </div>
    <script>
        document.getElementById('customerForm').addEventListener('submit', function (event) {
            event.preventDefault();

            // Get form values
            const customerName = document.getElementById('customerName').value;
            const customerID = document.getElementById('customerID').value;
            const bookPurchased = document.getElementById('bookPurchased').value;
            const quantity = document.getElementById('quantity').value;
            const cost = document.getElementById('cost').value;

            // Create a new row and cells
            const table = document.getElementById('customerTable').getElementsByTagName('tbody')[0];
            const newRow = table.insertRow();
            const nameCell = newRow.insertCell(0);
            const idCell = newRow.insertCell(1);
            const bookCell = newRow.insertCell(2);
            const quantityCell = newRow.insertCell(3);
            const costCell = newRow.insertCell(4);

            // Insert the values
            nameCell.innerText = customerName;
            idCell.innerText = customerID;
            bookCell.innerText = bookPurchased;
            quantityCell.innerText = quantity;
            costCell.innerText = cost;

            // Clear form fields
            document.getElementById('customerForm').reset();
        });

    </script>
</body>

</html>

Example: Basic Usage of parentsUntil()

Suppose you want to select all ancestor elements of the '.btn-submit' class element, stopping at the .container element, and excluding it.

JavaScript
describe('Using parentsUntil() method in Cypress', () => {
    it('test case',() => {
      cy.visit('http://127.0.0.1:5501/Web_Table/index.html') // URL of the application
      .get('.btn-submit').parentsUntil('.container').should('have.length', 2);
      });
      
    });

Explanation:

  • cy.get('.btn-submit'): Selects the button element with the class .btn-submit.
  • parentsUntil('.container'): Selects all ancestor elements of .container up to, but not including, the .container element.
  • should('have.length', 2): Asserts that two elements (i.e., .parent and .child) were selected.

Output:

If the .parent and .child elements are correctly selected as ancestors, the test will pass. If not, the test will fail.

parentUntil_final1
Output for basic usage of parentsUntil() method

Conclusion

The parentsUntil() method is one of the useful methods that help to maneuver through the tangled structures of the DOM and select ancestors until a given point in the ancestor hierarchy. With this technique in hand, you'll be able to develop more precise, effective, and more easily maintainable tests. Parent node navigation in the DOM is not a problem whether one is crawling up the hierarchy of deeply nested elements or filtering ancestors on some associated condition, as is provided by parentsUntil(). Its ability to specify a stopping point allows you to select only the relevant ancestors, making your test scripts cleaner and easier to manage.


Next Article
Article Tags :

Similar Reads