Cypress – focus() Method

On This Page What is Cypress Focus?How to Use cy.focus ()June 24, 2026 · 13 min read · Tool Comparison

Cypress & # 8211; focus () Method

Focus events in Cypress are significant for accessibility and user experience, peculiarly keyboard navigation.

Overview

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 ()

  • Simulate user interaction
  • Helps trigger centering case
  • Validates accessibility

Learn what the Cypress focus method is, its use cases, best exercise, and how to use it effectively with this comprehensive guide.

What is Cypress Focus?

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:

How to Use cy.focus ()

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:

cy.focus ()

To use cy.focus (), but chain it to a picker point a focusable element. This will sham the focus case on the component.

cy.get ('input [name= '' username ''] ') .focus ()

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:

cy.get ('input [name= '' username ''] ') .focus () .should ('have.class ', 'focused ')

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.

How to Focus an Element in Cypress (with Examples)

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.

1. Focusing on an Input Field

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.

// Focusing on a text stimulant field cy.get ('input [name= '' username ''] ') .focus ()

In this example:

  • cy.get (& # 8216; input [name= & # 8221; username & # 8221;] & # 8217;)command select the input battleground with the gens property& # 8220; username & # 8221;.
  • .focus () assume the action of centre on that input field.

2. Verifying Focus Style (e.g., CSS Focus Class)

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.

// Focusing on an input field and verifying the focus class cy.get ('input [name= '' username ''] ') .focus () .should ('have.class ', 'focused ')

Here, after focusing on the input field, Cypress checks if the focussed class is applied to the element.

3. Testing Focus on a Button

You can also use .focus () on early focusable component like button. This help ensure that focus work as expected for component extraneous form fields.

// Focusing on a button element cy.get ('button # submit ') .focus () .should ('have.css ', 'outline ', '1px solid rgb (0, 0, 255) ') // Assert focus scheme

In this example:

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

  • cy.get (& # 8216; button # submit & # 8217;)take the button with the id & # 8220;submit“.
  • .focus()Simulates focusing on the button.
  • .should (& # 8216; have.css & # 8217;, & # 8216; outline & # 8217;, & # 8216; 1px solid rgb (0, 0, 255) & # 8217;)checks if the button has a visible synopsis (commonly used as a focus indicator).

4. Testing Keyboard Navigation Focus

If you need to control the keyboard navigation flowing, use .focus () to ensure focus moves correctly when the user navigate between factor.

// 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 focused

Here,

  • First, the username input is focused.
  • Then, it checks that the password field is not yet focused.
  • cy.focus () .tab () sham pressing the Tab key to move focus to the next battlefield (watchword).
  • Finally, it control that the word stimulus field is now focused.

In cases where the typecast tab doesn ’ t work, you can use the experimentalcypress-plugin-tab.

Real-World Use Cases of Cypress .focus ()

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.

1. Validating Focus on Accessibility Elements

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.

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 ')})})

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.

2. Ensuring Focus on Input Fields after Validation

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).

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 ')})})

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:

3. Testing Focus on a Dropdown Menu

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.

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 ')})})

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 () vs cy.focused ()

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 ():

Featurecy.focus ()cy.focused ()
Usagecy.get (& # 8216; chooser & # 8217;) .focus ()cy.get (& # 8216; selector & # 8217;) .should (& # 8216; be.focused & # 8217;)
FunctionMoves the focus to the selected element.Checks if the element is presently focused.
Command TypeAction command (performs a focus action).Assertion bidding (verify the focussing state).
Return ValueNo homecoming value (focalize on the element).Returns an asseveration result (true/false).
Common Use CaseSimulating 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 TypeWorks on any focusable element.Asserts focus on an element, typically used for form fields, buttons, etc.

Challenges of cy.focus () and the Solutions

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 ().

  • Focus Not Working on Dynamic or Delayed Elements: In some cases, you may attempt to focus on an element that isn ’ t immediately available in the DOM (due to animations, lazy load, or delays in rendering). To work this, usecy.get() with a .should (& # 8216; be.visible & # 8217;) or .should (& # 8216; exist & # 8217;)assertion to insure the element is ready for interaction before applying .focus ().
  • Focus Applied But Not Reflected Visually: In some event, .focus () may successfully concenter an element, but you may not see any visible focus indicator (like a edge or outline), specially if CSS styles aren & # 8217; t correctly applied for focus states. You should always validate the optic focus state of ingredient to ensure that focussing behavior aligns with accessibility and design requirements. Use.should (& # 8216; have.css & # 8217;)to ascertain for a focus style, such as an outline.

Read More:

  • Issues with Focus on Non-Focusable Elements: Applying .focus () to non-focusable elements (like divs or spans that don ’ t have the tabindex dimension) may result in no visible issue or cause errors in your tests. Ensure you only use .focus () on elements that are focusable by nonpayment (e.g., inputs, buttons, links). If necessary, applytabindex= & # 8221; 0 & # 8243;to custom constituent to make them focusable.
  • Does not Trigger Focus Events: .focus () in Cypress doesn ’ t perpetually trigger native direction case like onFocus. This can make it difficult to test event listeners or side effects that depend on focus-related case. To ensure that the focus event is fully triggered, use the .trigger () method to manually fire a focus event after utilize .focus ().
  • Testing Focus with Complex Forms: In forms with multiple focusable elements or complex interactions (e.g., conditional profile, validation errors), centering may not move as await or may require additional interactions to trigger focussing change. Simulate user behavior by expend.tab()to quiz the sequential movement of centering between form fields. Combine .focus () with keyboard navigation simulation to check focusing run as expected in complex sort scenarios.
  • Focusing on Modal or Overlay Elements: When testing modal or overlays, focusing on the correct element can be tricky if the modal is not fully visible or shroud behind other DOM elements (like overlays). Ensure that the modal or overlay is visible and not obstructed by other elements before applying .focus (). Use.should (& # 8216; be.visible & # 8217;) or .scrollIntoView ()to get sure the modal is in the right state before centering.

Why Run Cypress Tests on BrowserStack Automate?

is a leading cross-browser try platform that grant you to run Cypress test on existent browser and devices in the cloud.

Talk to an Expert

Here are the key reasons why integrating Cypress with BrowserStack Automate can heighten your quiz scheme:

  • Access to Real Devices & amp; Browsers: Test across 3500+ real devices, OS and browsers, ensuring precise results for user interactions and compatibility.
  • Execution: Run tests concurrently across multiple environments, reducing execution time and speed up feedback cycles.
  • Seamless CI/CD Integration: Easily incorporate with similar, GitHub Actions, and, automating your exam as portion of the development workflow.
  • : Ensure your app works over multiple browsers (like Chrome, Firefox, Safari etc.) and their adaptation enhancing compatibility and user experience.
  • No Infrastructure Maintenance: Avoid managing testing infrastructure; BrowserStack handles everything, letting you focus on authorship tests.
  • Advanced : Access screenshots, picture transcription, and log to quickly troubleshoot tryout failures.
  • Scalability: Effortlessly scale your tests, from small projects to large suites, without infrastructure concern.
  • Cypress Dashboard Integration: Track test results in real time with the Cypress Dashboard, enabling better test management and quicker issue resolution.

Best Practices for Using Cypress Focus

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 ()

  • Focus on Focusable Element
  • Use Assertions After Focusing
  • Avoid Overusing .focus ()
  • Use .focus () with Delays When Needed
  • Focus on Focusable Elements: Always use .focus () on elements that are naturally focusable, such as input field, buttons, or links. Focusing on non-focusable constituent (like divs without tabindex) may lead to unexpected behaviour and unreliable test.
  • Use Assertions After Focusing: After using .focus (), it & # 8217; s a good practice to immediately control the component & # 8217; s state using affirmation like.should (& # 8216; be.focused & # 8217;). This insure that the element has have focus and behaves as expected.
  • Avoid Overusing .focus (): While .focus () is a powerful creature for simulating focus, avert overusing it unless necessary. Only use it when you need to test specific focus-related behaviors, such as ensuring elements receive focus on specific actions (like form submissions or keyboard navigation).
  • Use .focus () with Delays When Needed: In some cases, especially with animations or transitions, it may be necessary to expect for an component to get focusable before applying .focus (). Usecy.wait() or cy.get () .should ()to ensure the element is in the right state before focusing on it.

Conclusion

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.

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
30,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free