Cypress is an extremely advanced system in terms of the end-to-end testing that it can carry out over web applications. It allows DOM traversal operations, including the prev() method, which brings you to a previous sibling in the DOM. This method comes in handy if you want to perform operations on or check elements that are just after the selected element. We shall examine the prev() method more closely including how it is defined, its syntax and arguments and demonstrate examples where the method is applied.
Usages of `prev()` method
The prev() method in Cypress is concerned with fetching the preceding sibling of a node in review. This is very important when one intends to carry out actions and assertions of interest to the user on the elements that are immediately in a neighbourhood of the element of interest. For instance, if one has to check the element that comes before a certain element consists of some content or attributes, a sense of prev() is very helpful in selecting that and many more elements relatively quickly.
The common critical implementations of the prev() method are:
- Moving to and demanding action of another DOM entity that is a sibling of the one within that which has been selected but is closer to the left.
- Carrying out operations to check the content of the element that is an immediate previous element of the same in a list, table or any other systematic ways.
- Eliminating intricate CSS selectors in test scripts to simplify tests.
Syntax
Syntax for `prev()` method in Cypress is:
cy.get(selector).prev(prevSelector)
- `selector` : This selector represents the element from which you want to dearch for the previous sibling.
- `prevSelector`: This is an optional filter selector which constricts the selection of the previous sibling according to the specifications.
Arguments
- selector: The CSS selector which is used to choose the target element.
- prevSelector: An optional CSS selector which is used to filter out the previous sibling element. By default, prev() will select the immediate previous sibling.
Examples
These example shows the working of `prev()` method. Here's the application code that we will be using as a sample for performing prev() 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>
Example 1: Basic Usage of prev()
Suppose you want to choose the heading that comes immediately before the element with id customerTable. We can do this in Cypress with the help of the given code.
JavaScript
describe('Using prev() method in Cypress', () => {
it('test case',() => {
cy.visit('http://127.0.0.1:5501/Web_Table/index.html') // URL of the application
.get('#customerTable').prev().should('have.class', 'heading');
})
});
Explanation:
- cy.get('#customerTable'): Selects the element with the id customerTable.
- prev(): Selects the previous sibling element, which in this case is the element with class .heading.
- should('have.class', 'heading'): Asserts that the previous sibling element has the class heading.
Output:
If the .heading element is correctly identified as the previous sibling, the assertion will pass. Otherwise, it will fail.
Output for example of Basic Usage of prev()Example 2: Using prev() with a Selector
Suppose you want to filter out the previous sibling based on certain specifications. Here in this example, you want to filter out the previous sibling of .btn-submit element but only if it has the class .form, then we can achieve it in Cypress by the following code.
JavaScript
describe('Using prev() 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').prev('.form').should('have.id', 'cost');
})
});
Explanation:
- cy.get('.btn-submit'): Selects the list item with the class .btn-submit.
- prev('.form'): Filters the previous sibling to ensure it has the class .form.
- should('have.id', 'cost'): Asserts that the selected previous sibling have id "cost".
Output:
If the previous sibling of the class element ".btn-submit' which is ".form " class element have id ".cost" then the test will pass, otherwise the test fails.
Output for using prev() with a SelectorConclusion
The Cypress ‘prev()’ method is quite important when dealing with navigating the DOM and referencing the immediate preceding sibling of an element. With the help of this method, your test scripts can be written in a less cumbersome way and your assertions can be more specific and sharper. When dealing with lists, tables or any other elements arranged one after the other prev() method allows you to find your way around the DOM and manipulate and test elements that are near each other.
Similar Reads
Cypress - prevAll() Method
The prevAll() method in Cypress is a powerful tool for traversing the DOM to interact with or validate elements that come before a specified element. This method is particularly useful when you need to select all preceding siblings of a given element within the same parent. By traversing backward th
8 min read
Cypress - parent() Method
interactionCypress is a feature-rich end-to-end testing tool that eases the process of writing tests for web applications by exposing a rich set of functionality that allows interaction with the DOM. One such functionality is the parent() method out of the various DOM methods which enables you to ac
6 min read
Cypress - spread() Method
The spread() method in Cypress is a utility function provided by the Bluebird library, which Cypress uses internally to handle promises. It allows you to handle multiple promise results more elegantly by spreading them out into separate arguments, making your code cleaner and easier to read.Usages o
3 min read
Cypress - prevUntil() Method
The prevUntil() method in Cypress is a powerful tool for selecting all preceding sibling elements between a specified element and another target element (or until no more siblings are found). This method is particularly useful when you need to traverse backwards through sibling elements based on spe
6 min read
Cypress - pause() Method
The pause() method in Cypress is used to pause the test execution at any point, allowing developers to inspect the application state during testing. This is particularly useful for debugging and verifying interactions within the application.Syntax:cy.pause()Usage of pause() MethodThe pause() method
4 min read
Cypress - url() Method
Cypress is a popular testing framework for web applications. It provides a lot of useful methods to interact with web pages, including the url() method. In this article, we will explore the url() method in Cypress, its usage, syntax, arguments, and examples.UsagesThe url() method is used to get the
2 min read
Cypress - spy() Method
In Cypress, spy() helps you monitor and assert the behaviour of functions or methods. Itâs a valuable tool for testing that your application interacts with functions or components as expected. Spies are typically used to verify internal logic, such as ensuring that a particular function gets called
3 min read
Cypress - reload() Method
The reload() method in Cypress allows you to current page in your test. This is particularly useful when testing page reload the behavior or when you want to reset the page to its original state. In this article, we will walk through what reload() method does, its syntax, use cases, and step-by-step
4 min read
Cypress - next() Method
The next() method in Cypress allows you to select the immediately following sibling of a DOM element. This is useful when you want to interact with an element that comes directly after another in the DOM structure. Itâs commonly used when navigating through lists, tables, forms, or any other HTML st
4 min read
Cypress - root() Method
The root() method in Cypress is a powerful tool used to select the root element of the DOM, which is typically the <html> element. This method is especially useful for starting interactions or traversals from the top level of the document, ensuring that all subsequent commands are scoped to th
5 min read