Cypress closest command

Profile picture for user arilio666

We have a special command in cypress called closest where we will select DOM elements closest to an element or we can say, class.

  • Kinda fetching the class of the element for example closest to the ancestor of the element present.
  • The behavior of this command looks and feels and works closely to that of the Jquery.
<ul class="list">
  <li class="list-item">
    <span class="medal">14</span>
    Events
  </li>
  <li class="group-item">
    <span class="versal-badge">54</span>
    Hello
  </li>
</ul>
cy.get('.versal-badge')
  .closest('ul')
  .should('have.class', 'list')
  • So this is closest command used from this simple example we can conclude that it fetches the element of versal-badge of which its ancestor is ul tag and that ul tag contains a class called a list.
  • This is basically what the closest command is.

Another example pertaining to the closest command is:

cy.get('p.success').closest('.banner')
  • Here the closest command works like, get the closest element of the tag.class(p.success) with class 'banner'.

Syntax

cy.get('selector').closest('ancestor/closest elements')

This is how we should declare the closest command and is the right approach and correct form of syntax to follow through.

Here in this article, we will be doing a real-time scenario use of the closest command.

Well, enough chit-chat let's get to business.

Example:

For demo purposes, we will be automating our respective article site https://www.programsbuzz.com/

Today we will be doing the following things:

Step 1:- We need to visit the page.
Step 2:- Click on the ask doubt menu.
Step 3:- Get the title of the page with the closest command and log it using then.

Sounds fun right? let's dive.

describe('Automate ProgramsBuzz Site',()=>{
    before(() => {
        cy.visit('https://www.programsbuzz.com/')
        })
    it('Log Title Name',()=>{
        cy.contains('Ask Doubt').click()
        cy.get('h1.page-title').closest('div').then($log => {
            const fLog = $log.text()
            cy.log(fLog)
        })
    })
})
  • For a more clear understanding let us take a look at our DOM.

  • From the DOM it is very clear that we have taken the tag.class which is h1.page-title.
  • We are getting this element that is closest to the ancestor of the div tag.

Simple right?

  • Then we are using the then command to create a yielding thing which it does and extract the yielded result via the log object and log it.

  • Now as we can see that the page title is now logged according to our use case with the closest ancestor div tag of the h1 tag and its class.
  • This is how closest works and it is pretty handy when it comes to the family isolation concept of the DOM elements.