Cypress – focus() Method
On This Page What is Cypress Focus?How to Use cy.focus ()June 24, 2026 · 13 min read · Tool Comparison
Focus events in Cypress are significant for accessibility and user experience, peculiarly keyboard navigation. What is Cypress.focus () In Cypress, cypress.focus () is a command that helps spark the focus on a specific DOM element, such as a button, input field, or alike focusable factor. It simulates user interaction by programmatically focusing the element, countenance you test behaviors like keyboard navigation, availability, and input field interaction. Why Use Cypress.focus () Learn what the Cypress focus method is, its use cases, best exercise, and how to use it effectively with this comprehensive guide. Cypress.focus ()is a bid that imitate centre on an component within a web application during. It ensures that direction can be programmatically utilize to focusable elements, such as input fields, buttons, or tie-in. The.focus () command is particularly useful in testing scenarios where the direction event is key, such as in keyboard navigation proof or checking that ocular cues (such as focus outlines) are supply correctly. Using cy.focus () countenance examiner to interact with elements as they would be used by the user, thereby confirming covering behavior under focus. This is oft combined with assertion to see the focus state, ensuring focus transitions are right in scenarios that involve various user conduct and are accessible. Read More: The cy.focus () command is use in to simulate focusing on a specific factor during automated tests. It can be applied to focusable ingredient like stimulation fields, button, and links to verify focus-related behavior. Syntax: To use cy.focus (), but chain it to a picker point a focusable element. This will sham the focus case on the component. This command will focus on the input field with the gens attribute & # 8220; username & # 8221;. The cy.focus () command make not expect any arguments. It operates on the element selected via Cypress commands likecy.get(), cy.contains (), or cy.find(). You must locate a focusable element before applying.focus() to it. Example with an assertion: In this instance, after focusing on the username input field, the examination assay if the element has a focussed class applied. cy.focus ()does not spark events likeonFocus or focusnatively; it just moves the focus to the targeted ingredient for testing design. In Cypress, you can use the .focus () method to simulate focusing on an element, such as an input field, button, or any other focusable element. This is particularly utilitarian when testing interaction that rely on focus case, such as keyboard seafaring, form field validation, or visual focus styles. Suppose you want to test if an input battlefield can be centre correctly. You can use .focus () to model the focus event on that element. In this example: You might desire to control that a CSS stratum (like focused) is utilize when the element is focused. You can use.should()to assert the expected result. Here, after focusing on the input field, Cypress checks if the focussed class is applied to the element. You can also use .focus () on early focusable component like button. This help ensure that focus work as expected for component extraneous form fields. In this example: For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users. If you need to control the keyboard navigation flowing, use .focus () to ensure focus moves correctly when the user navigate between factor. Here, In cases where the typecast tab doesn ’ t work, you can use the experimentalcypress-plugin-tab. The Cypress .focus () method is valuable for testing scenario requiring centering management and keyboard piloting and ensuring are met. Below are a few real-world use example where .focus () can be used in machine-controlled examination, along with example. Focus management is crucial for user who rely on keyboard navigation or. When exploiter interact with component like modals, dropdowns, or synergistic lists, it & # 8217; s essential to ensure that focus is properly set and that constituent are accessible. Read More: You can essay that the focussing is correctly locomote to a modal window when it & # 8217; s opened and that the direction return to the correct element when the modal is closed. After clicking the push to open the modal(cy.get (& # 8216; button # openModal & # 8217;) .click ()), the test checks that the average receives focus(cy.get (& # 8216; .modal & # 8217;) .should (& # 8216; be.focused & # 8217;)). After closing the modal, the tryout asserts that the focussing returns to the original button that open the modal. Sometimes, after a user submits a form, the focus should be returned to an invalid input field for correction. This is especially useful in applications that provide inline validation. After a descriptor submission with invalid input, you can test that the focus is returned to the initiatory invalid field (for example, an email input with an invalid formatting). The form is subject with an invalid email(cy.get (& # 8216; input [name= & # 8221; email & # 8221;] & # 8217;) .type (& # 8216; invalidemail & # 8217;)). After submission, Cypress verify that the email stimulant has an & # 8220; invalid & # 8221; class and that the focus is returned to the invalid email field using .focus (). Read More: In applications with complex UI components like dropdowns, it is critical for accessibility to ensure that the focus remains on the dropdown after opening and behaves as expected when using the keyboard to sail alternative. Here, you can verify whether the focus moves correctly between dropdown item when the exploiter pilot through the options using the keyboard. The dropdown is opened using.click()on the toggle button. Cypress simulates the down pointer key press using.type (& # 8216; {downarrow} & # 8217;)to sail the dropdown items. The tryout swan that focus moves aright between the particular as the arrow key is pressed. cy.focus () is use to set the focus, while cy.focused () is used to control whether a specific element has the centering. Here are the key differences between cy.focus () and cy.focused (): While cy.focus () is worthful for simulating focussing events in Cypress, you may meet certain challenges during testing. Below are some common challenges and their solutions to ensure effective and honest use of .focus (). Read More: is a leading cross-browser try platform that grant you to run Cypress test on existent browser and devices in the cloud. Here are the key reasons why integrating Cypress with BrowserStack Automate can heighten your quiz scheme: When using the .focus () method in Cypress, it & # 8217; s significant to postdate better practices to ensure reliable and efficient tryout, particularly when dealing with user interactions and accessibility feature. Below are a few best practices to keep in judgement: Best Practices for using cypress.focus () Cypress .focus () method is vital for testing user interactions and handiness, ensuring focus management works as expected across forms, button, and modals. Integrating Cypress with BrowserStack Automate enhances prove by providing access to a vast existent device cloud, cross-browser compatibility, and parallel test execution. This combination streamline the test process, improves test reportage, and helps deliver high-quality applications faster, ensuring seamless user experience and racy availability compliance. Understanding Cypress Use Cases Tool Comparisons On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Cypress & # 8211; focus () Method
Overview
What is Cypress Focus?
How to Use cy.focus ()
cy.focus ()
cy.get ('input [name= '' username ''] ') .focus ()cy.get ('input [name= '' username ''] ') .focus () .should ('have.class ', 'focused ')How to Focus an Element in Cypress (with Examples)
1. Focusing on an Input Field
// Focusing on a text stimulant field cy.get ('input [name= '' username ''] ') .focus ()2. Verifying Focus Style (e.g., CSS Focus Class)
// Focusing on an input field and verifying the focus class cy.get ('input [name= '' username ''] ') .focus () .should ('have.class ', 'focused ')3. Testing Focus on a Button
// Focusing on a button element cy.get ('button # submit ') .focus () .should ('have.css ', 'outline ', '1px solid rgb (0, 0, 255) ') // Assert focus scheme4. Testing Keyboard Navigation Focus
// Focusing on the first input field and pressing Tab to travel focus cy.get ('input [name= '' username ''] ') .focus () cy.get ('input [name= '' password ''] ') .should ('not.be.focused ') cy.focus () .tab () // Simulate pressing the Tab key to move focus to the future field cy.get ('input [name= '' password ''] ') .should ('be.focused ') // Verify the password input is now focusedReal-World Use Cases of Cypress .focus ()
1. Validating Focus on Accessibility Elements
describe ('Modal Focus Management ', () = & gt; {it ('should focus the modal and return focussing to the push after closing ', () = & gt; {// Visit the page with the modal cy.visit ('https: //example.com ') // Click the button to open the modal cy.get ('button # openModal ') .click () // Ensure the modal receives focus cy.get ('.modal ') .should ('be.visible ') .focus () cy.get ('.modal ') .should ('be.focused ') // Ensure modal is focalise // Simulate shutting the modal cy.get ('.modal-close ') .click () // Ensure focus homecoming to the open modal button cy.get ('button # openModal ') .should ('be.focused ')})})2. Ensuring Focus on Input Fields after Validation
describe ('Form Validation and Focus Return ', () = & gt; {it ('should return focus to the first invalid input after form submission ', () = & gt; {// Visit the variety page cy.visit ('https: //example.com/signup ') // Submit the sort with invalid data (e.g., invalid email) cy.get ('input [name= '' email ''] ') .type ('invalidemail ') cy.get ('button [type= '' submit ''] ') .click () // Ensure the email field is invalid and refocused cy.get ('input [name= '' email ''] ') .should ('have.class ', 'invalid ') cy.get ('input [name= '' email ''] ') .focus () .should ('be.focused ')})})3. Testing Focus on a Dropdown Menu
describe ('Dropdown Keyboard Navigation ', () = & gt; {it ('should focus the right dropdown items when expend arrow key ', () = & gt; {// Visit the page with the dropdown cy.visit ('https: //example.com ') // Open the dropdown cy.get ('.dropdown-toggle ') .click () // Move focus to the first item using the down pointer key cy.focus () .type (' {downarrow} ') cy.get ('.dropdown-item ') .first () .should ('be.focused ') // Move focus to the next particular cy.focus () .type (' {downarrow} ') cy.get ('.dropdown-item ') .eq (1) .should ('be.focused ')})})cy.focus () vs cy.focused ()
Feature cy.focus () cy.focused () Usage cy.get (& # 8216; chooser & # 8217;) .focus () cy.get (& # 8216; selector & # 8217;) .should (& # 8216; be.focused & # 8217;) Function Moves the focus to the selected element. Checks if the element is presently focused. Command Type Action command (performs a focus action). Assertion bidding (verify the focussing state). Return Value No homecoming value (focalize on the element). Returns an asseveration result (true/false). Common Use Case Simulating focus in tests (e.g., form interaction, keyboard navigation). Verifying if an element focused is typically used in assertions after activeness. Can be chained? Yes, with early commands (like .type (), .should ()). Yes, it can be chained with other assertions. Element Type Works on any focusable element. Asserts focus on an element, typically used for form fields, buttons, etc. Challenges of cy.focus () and the Solutions
Why Run Cypress Tests on BrowserStack Automate?
Best Practices for Using Cypress Focus
Conclusion
Useful Resources for Cypress
Related Guides
Automate This With SUSA
Test Your App Autonomously