Focus on a DOM element.
cy.get('input').first().focus() // Focus on the first input
cy.focus('#search') // Errors, cannot be chained off 'cy' cy.window().focus() // Errors, 'window' does not yield DOM element
Pass in an options object to change the default behavior of
||Displays the command in the Command log|
||Time to wait for
.focus()yields the same subject it was given from the previous command.
// yields the <textarea> for further chaining cy.get('textarea').focus().type('Nice Product!').blur()
.focus() is not implemented like other action commands, and does not follow the same rules of waiting for actionability.
.focus() is just a helpful command which is a simple shortcut. Normally there’s no way for a user to “focus” an element without causing another action or side effect. Typically the user would have to click or tab to this element.
Oftentimes it’s much simpler and conveys what you’re trying to test by just using
If you want the other guarantees of waiting for an element to become actionable, you should use a different command like
If there is currently a different DOM element with focus, Cypress issues a
blur event to that element before running the
Ensure the element you are trying to call
.focus() on is a focusable element.
If you see this error, you may want to ensure that the main browser window is currently focused. This means not being focused in debugger or any other window when the command is run.
Internally Cypress does account for this, and will polyfill the blur events when necessary to replicate what the browser does. Unfortunately the browser will still behave differently when not in focus - for instance it may throttle async events. Your best bet here is to keep Cypress focused when working on a test.
.focus()requires being chained off a command that yields DOM element(s).
.focus()requires the element to be able to receive focus.
.focus()will automatically wait for assertions you've chained to pass.
.focus()can time out waiting for assertions you've added to pass.
Focus the textarea
The commands above will display in the Command Log as:
When clicking on the
focus command within the command log, the console outputs the following: