focus
Focus on a DOM element.
Syntax
.focus()
.focus(options)
Usage
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
Arguments
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 |
Yields
.focus()
yields the same subject it was given..focus()
is a command, and it is unsafe to chain further methods that rely on the subject.
Examples
No Args
Focus on an input
cy.get('[type="input"]').focus()
Focus, type, and blur a textarea
// yields the <textarea> for further chaining
cy.get('textarea').focus().type('Nice Product!').blur()
Notes
Actionability
Focus is not an action command
.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()
.
Blur Events
Cypress blurs other focused elements first
If there is currently a different DOM element with focus, Cypress issues a
blur
event to that element before running the .focus()
command.
Focusable
Can only be called on a valid focusable element
Ensure the element you are trying to call .focus()
on is a
focusable element.
Timeouts
Can time out because your browser did not receive any focus events
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.
Rules
Requirements
-
.focus()
requires being chained off a command that yields DOM element(s). -
.focus()
requires the element to be able to receive focus.
Assertions
-
.focus()
will automatically wait for assertions you have chained to pass
Timeouts
-
.focus()
can time out waiting for assertions you've added to pass.
Command Log
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: