title | description | sidebar_label | slug | componentSpecific |
---|---|---|---|---|
cy.press() | Cypress Documentation |
Trigger native key events in your application to simulate keyboard interactions. |
press |
/api/commands/press |
false |
Trigger native key events in your application to simulate keyboard interactions.
A keydown
, press
, and keyup
event will be dispatched directly to the browser window.
Unlike cy.type()
, which is best for typing character keys, cy.press()
will dispatch real keyboard events rather than simulated ones. This command is especially useful when testing focus management and keyboard navigation patterns which are critical for accessibility testing and great keyboard UX.
Currently, the only key supported is Tab
.
:::caution
Supported Browsers: This command is supported in chromium browsers and Firefox versions >= v135. WebKit is not supported. This command will fail if executed in a browser that does not support it.
:::
cy.press(key)
cy.press(key, options)
interface PressCommand {
(
key: KeyPressSupportedKeys,
options?: Partial<Cypress.Loggable> & Partial<Cypress.Timeoutable>
): void
}
Correct Usage
cy.get('input.first').focus()
cy.press(Cypress.Keyboard.Keys.TAB)
cy.get('input.second').should('have.focus')
Incorrect Usage
cy.get('input.first').focus()
cy.press(Cypress.Keyboard.Keys.TAB)
// Errors because press yields null
.should('have.focus')
key (String)
The key to press. The supported values are available on Cypress.Keyboard.Keys
, and may change from time to time. It's recomended that you reference these values from Cypress.Keyboard.Keys
rather than passing in a string.
Reference | Value |
---|---|
Cypress.Keyboard.Keys.TAB |
"Tab" |
options (Object)
Pass in an options object to change the default behavior of .press()
.
Option | Default | Description |
---|---|---|
log |
true |
Displays the command in the Command log |
timeout |
defaultCommandTimeout |
Time to wait for cy.press() to resolve before timing out |
cy.press()
yieldsnull
.
it('moves focus to the next form element when pressing Tab', () => {
cy.visit('/my-login')
cy.get('input.email').type('username')
cy.press(Cypress.Keyboard.Keys.TAB)
cy.get('input.password').should('have.focus')
})
it('autocompletes search input when pressing Tab', () => {
cy.get('[data-cy="search"]').type('cy')
cy.press(Cypress.Keyboard.Keys.TAB)
cy.get('[data-cy="search"]').should('have.value', 'cypress')
})
By dispatching native keyboard events to the browser, this command will cause the browser to enter Transient activation state.
If your application prevents the default behavior of the beforeunload
event, this may cause issues when navigating away from the current page.
Version | Changes |
---|---|
14.3.0 | Added the .press() command |