The Cypress focused command fetches the DOM element that is currently focused and perform operations on that element.
Syntax
cy.focused()
cy.focused(options)
Arguments Used In Focus Command
Options:
- log: To display the command in the command log.
- timeout: Time to wait for cy.focused() to resolve before timing out
Correct Use Of Focused
cy.focused()
Yields element currently in focus.
What does it yield?
cy.focused() will yield the DOM elements it found.
What does it require?
It requires to be chained off a command that yields DOM elements.
How does it assert?
- cy.focused() will automatically retry until the elements are present visibly.
- It will also retry until all chained assertions have passed.
How does it timeout?
- cy.focused() can timeout waiting for the elements to be present visibly in the DOM.
- cy.focused() can also time out waiting for assertions added to pass the test.
Cypress Focused Command Example
Let us see a real-time scenario.
it('Type Username And Password',()=>{
cy.visit('https://www.programsbuzz.com/user/login')
cy.get('form').within(()=>{
cy.xpath("//input[@id='edit-name']").type('Naruto')
cy.focused().should('have.attr','id').and('eq','edit-name')
cy.xpath("//input[@id='edit-pass']").type('Boruto')
cy.focused().should('have.attr','id').and('eq','edit-pass')
cy.xpath("//input[@id='edit-submit']").click()
})
})
Console View:
Output:
We can see that using the focused command targeted the username and password field focused its DOM element and yielded it. This is confirmed by asserting the same for the returned attribute from the focus in the console view.