Skip to main content

Cypress focus Command

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.
Tags
Submitted by arilio666 on February 10, 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.