Cypress - closest() Method
Last Updated :
05 Sep, 2024
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.
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.
Example of using `closest()` while having multiple elementsConclusion
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.
Similar Reads
Cypress - clear() Method The Cypress clear() method is a powerful tool used to clear the values of form elements, such as input fields and text areas. In this article, we will explore the Cypress clear method in detail, including its syntax, usage, and examples.SyntaxThe syntax for the Cypress clear method is as follows:cy.
2 min read
Cypress - clock() Method The clock() method in Cypress is used to control and manipulate the clock in our tests. This allows developers to test time-dependent code more effectively by controlling the passage of time and simulating the behavior of timers and intervals.Syntax:cy.clock()Usage of Cypress - clock() MethodThe clo
4 min read
Cypress - as() Method The as() method in Cypress is used to create aliases for elements or other values, which can then be referenced later in your tests. This is useful for making your tests more readable and efficient by avoiding repetitive code and simplifying complex selectors.Table of ContentUsageSyntaxArgumentsExam
4 min read
Cypress - clearCookies() Method Cookies are small pieces of data stored by the browser that help maintain user sessions, track user preferences, and store other information. In automated testing with Cypress, managing cookies is essential for ensuring clean test environments and simulating different user scenarios. The clearCookie
4 min read
Cypress - click() Method The click() method in Cypress is a command that simulates a click event on an element. It can be used to interact with web pages in a way that mimics how a user would click on an element. This method can also be used to test web applications.Usages of Cypress - click() MethodIt simulates a click eve
3 min read
Cypress - check() Method Cypress is a popular testing framework for web applications. It provides a lot of useful methods to interact with web pages, including the check() method. In this article, we will explore the check() method in Cypress, its usage, syntax, arguments, and examples.Usages of Cypress - check() MethodThe
3 min read
Cypress - contains() Method Cypress is a popular testing framework for web applications. It provides a lot of useful methods to interact with web elements, one of which is the contains() method. In this article, we will explore the contains() method in Cypress, its usage, and examples.UsagesThe contains() method checks if an e
2 min read
Cypress - Childern() Method Cypress is a widely adopted end-to-end testing framework that assists developers in creating web app tests that they can trust. One of the useful traversal methods provided by Cypress is the children() method. This method enables the user to gather all the direct descendant child elements of any sel
6 min read
Cypress - blur() Method When you use the blur() method in Cypress, it's like clicking away from a specific part of a webpage, like an input field. This helps simulate how a real user would interact with the page. It's especially useful when testing websites that do certain things when you focus or unfocus on certain parts
2 min read
Cypress - eq() Method The eq() method in Cypress is a powerful utility that allows you to select a specific element from a group of elements based on its index. This method is particularly useful when you need to interact with or make assertions on a specific element within a collection of elements that share the same se
3 min read