title | description | sidebar_label |
---|---|---|
focus | Cypress Documentation |
Focus on a DOM element in Cypress. |
focus |
Focus on a DOM element.
It is unsafe to
chain further commands that rely on the subject after .focus()
.
.focus()
.focus(options)
Correct Usage
cy.get('input').first().focus() // Focus on the first input
Incorrect Usage
cy.focus('#search') // Errors, cannot be chained off 'cy'
cy.window().focus() // Errors, 'window' does not yield DOM element
options (Object)
Pass in an options object to change the default behavior of .focus()
.
Option | Default | Description |
---|---|---|
log |
true |
Displays the command in the Command log |
timeout |
defaultCommandTimeout |
Time to wait for .focus() to resolve before timing out |
.focus()
yields the same subject it was given.- It is unsafe
to chain further commands that rely on the subject after
.focus()
.
cy.get('[type="input"]').focus()
// 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 a helpful command used as a 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 using .focus()
directly is more concise and conveys what you're
trying to test.
If you want the other guarantees of waiting for an element to become actionable,
you should use a different command like .click()
.
If there is currently a different DOM element with focus, Cypress issues a
blur
event to that element before running the .focus()
command.
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 have chained to pass.
.focus()
can time out waiting for assertions you've added to pass.
Focus the textarea
cy.get('[name="comment"]').focus()
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: