Cypress focus Command

Profile picture for user arilio666

When a particular element needs to be focused, the focus command is used in cypress to aim it precisely and get the job done.

Syntax

.focus()
.focus(options)

Arguments Used In Focus Command

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

Correct Use Of Focus

cy.get('#id').focus()

Focuses on the id element.

Wrong Use Of Focus

cy.focus()
cy.window.focus()
  • Only should be chained up with the command which yields element.
  • Focus command yields the same subject the previous command yields.
  • It requires the element to focus.
  • It will wait automatically for the assertions chained to pass.
  • It can also time out waiting for assertions.

Example

Let us see a realtime scenario

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

    })
    it('Should click Side bar',()=>{

        //cy.get('.bar-style').click()
        cy.get('#mce-EMAIL').scrollIntoView()
        cy.get('form').within(()=>{
           // cy.get('p').should('contain','Never Miss Anything From Multikart By Signing Up To Our Newsletter.')
            cy.document().its('body').find('p').should('contain','Never Miss Anything From Multikart By Signing Up To Our Newsletter.')
            //cy.root().closest("div[class='subscribe'] div")
            cy.get('#mce-EMAIL').type('mama@gmail.com')
        })
    })
})
  • This is a simple temporary escape method.
  • We can notice that we are closing a popup after visiting the site.
  • In this case, the true aim is to close the popup.
  • Because without closing the functions after, the code won't work.
  • In this case, we are focusing on the element '.close.'

  • We can see that it has focused and click on the close button of the popup.
  • This is one of the ways we can use the focus command.