Open In App

Cypress - closest() Method

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

Being an end-to-end testing tool, Cypress eases the work of web application testing for developers without being overly technical. One of the useful methods provided by Cypress is the closest() method. Imagine that you are working with an application where you need to move up the node tree in search of a parent node satisfying certain criteria. In the present article, we will take a closer look at the closest() method types as well as their usage, syntax, and arguments, as well as practical application for clearer understanding.

Usage of `closest()` method

In cypress, the closest() method is used to search for the parent element which matches the selector passed as an argument. In this scenario, this method comes very handy as it solves the dependency of child elements with their parent elements in nested elements. It can come in handy for instance when you want to make a click, type, or assertions on an element that is situated inside another one.

Given below are the key use cases of the closest() method are the following:

  • Finding the nearest of the particular parent element.
  • Preserving the scoping of an element within its context.
  • Avoiding excessive element traversing by sticking to relevant parents.

Syntax

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

cy.get(selector).closest(closestSelector)
  • `selector' : This selector represents the element(s) you want to start from.
  • `closestSelector`: This selector represents for the closest ancestor element you want to find.

Arguments:

  • selector: This CSS selector is used to select the initial elements set.
  • closestSelector: This selector is used to select the closest matching ancestor element.

Examples

Here's the application code that we will be using as a sample for performing closest() 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>
        <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>
    <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>


Let's begin by examining the example and see how the closest() method should be used.

Example 1: Basic Usage of `closest()`

Suppose you need to find the `.cus_form` element that is closest to the `.btn-submit` button. Here's how you can achieve that using Cypress:

JavaScript
describe('Using closest() 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').closest('.cus_form').should('have.class', 'cus_form');

    })
});

Explanation:

  • cy.get('.btn-submit'): Selects the button element with the class .btn-submit.
  • closest('.cus_form'): Traverses up the DOM tree to find the nearest ancestor with the class .cus_form.
  • should('have.class', 'cus_form'): Asserts that the closest ancestor has the class cus_form.

Output:

If the cus_form element is found as the closest ancestor, then the assertion will be successfull else it will fail.

Here's the output for the above example.

closest1
Output for Basic usage of closest()

Example 2: Using `closest()` while having multiple elements

Suppose you need to find the `.container` element that is closest to the `.btn-submit` button. Here's how you can achieve that using Cypress:

JavaScript
describe('Using closest() 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').closest('.container').should('exist');

    })
});

Explanation:

  • cy.get('.btn-submit'): Selects the button element with the class .btn-submit.
  • closest('.container'): Finds the closest ancestor with the class .container.
  • should('exist'): Asserts that the closest .container element exists in the DOM.

Output:

If the `.container` lement is found as the closest ancestor to `.btn-submit`, then the test is successfull else the test fails.

closest2
Example of using `closest()` while having multiple elements

Conclusion

The closest() method in Cypress is useful to traverse back the list of elements that have been manipulated and generates the nearest ancestor based on some parameters. Knowing how to apply this particular method judiciously will certainly assist in developing better more intelligent tests for web applications. There are cases whether simple or complicated there are cases where closest() would be applicable for general test cases by targeting relevant parent elements therefore safeguarding the accuracy and the manageability of the tests as well.

What is the use of `closest()` method in Cypress?

The closest() method is employed in identifying the most immediate relative that corresponds to a certain selector in the DOM.

Can you use `closest()` to find multiplle ancestors?

No, the closest() method works in a way that it returns the first matching ancestor and there will be no returns of multiple closest() ancestors. Several such queries would require that you chain several closest() calls or other methods.

Does `closest()` method works with all CSS selectors?

Yes, `closest()` works with any valid CSS selector to find the matching ancestor.

What happens if `closest()` doesn't find a matching ancestor?

When no ancestor that satisfies the conditions is available, closest() gives back an empty set which will thus fail all the conditions after it in the aspirational windows.

Can we use `closest()` on multiple elements simultaneously?

Sure, the closest() method can be called on a set of elements and it will get the closest ancestor for every element from the collection.


Next Article
Article Tags :

Similar Reads