Skip to main content

Cypress last Command

So within a set of DOM elements, the last command fetches the last DOM element from that set. This behavior of the last command in cypress is that of the exact behavior of the jquery last command.

Syntax:

.last()
.last(options)

Some of the options we can include in the command can be a timeout, log, etc.

  • Log: To display the command in the command log.
  • Timeout: Wait for some particular thing to get finished before timing out.

Correct Use

cy.get('li').last()

This gets the last element of the li tag.

Incorrect Use

cy.last();

It cannot be chained up with cy directly.

Let us see a sample example of how this works:

<ul>
  <li class="uno">Hola1</li>
  <li class="tres">Hola2</li>
  <li class="des">Hola3</li>
  <li class="tez">Hola4</li>
</ul>
cy.get('li').last()

This command for the above DOM elements yields <li class="tez">Hola4</li> because this element is in the last place.

Now let us see a real-time example of automating our traditional http://autopract.com/#/home/fashion.

So let us get back to our last command.

Here are the test steps of what we are about to do:

  1. Visit the site.
  2. Close the emerging popup.
  3. Click the side panel to reveal menu items.
  4. Print, last item text using the last command.

Let us dive in then!!

describe('Automate AutoPract',()=>{
    it('Should load the url',()=>{
        cy.visit('http://www.autopract.com/#/home/fashion')
        
    })
    it('Should close POPUP',()=>{
        cy.get('.close').click()

    })
    it('Should click Side bar and get last item text',()=>{
        cy.get('.bar-style').click()
        cy.get('#sub-menu').find('li').last().then($log => {
            const fLog = $log.text()
            cy.log(fLog)
        })

    })
})
  • So, first of all, we will visit and close the popup which appears.

  • As you can see here, the visible DOM elements in the id sub-menu cover all the items in the menu bar.
  • Under that, the li tags are the list of items in which we will cover the last element out of this DOM.
  • So we used the find command to find li tag within sub-menu id and fetch the last element.
  • We used the then command to get the yield of last and store the text in a variable only to log it.

  • Here, we can see that it fetched the kitchen item, which is the last menu item in that menu bar.
Tags
Submitted by arilio666 on January 11, 2022

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.