Open In App

Cypress - prev() Method

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

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.

prev1
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.

prev2
Output for using prev() with a Selector

Conclusion

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.


Next Article

Similar Reads