Simulating Key Press Events in Cypress for Webpage Test Automation

Simulating Key Press Events in Cypress for Webpage Test Automation

3 July 2024 Stephan Petzl Leave a comment QA

When working on webpage test automation using Cypress, you may encounter scenarios where you need to simulate a key press event, such as pressing the ESCAPE key. While Cypress provides a type() method for typing into DOM elements, simulating a simple key press without involving a DOM element can be challenging.

Understanding the Problem

The primary issue arises from the fact that Cypress’s type() method requires chaining off a DOM element. For example:


This approach works when you want to type into a specific element, but it does not suffice for simulating a global key press event.

Attempted Solutions

Several solutions have been proposed, including:

  • Using cy.get('body').type('{esc}');
  • Triggering keydown events directly on the body element:
cy.get('body').trigger('keydown', { keyCode: 27, which: 27 });

However, these methods may not always work due to Cypress’s event handling specifications.

Effective Solution

The most effective solution found involves triggering both keydown and keyup events with a brief wait time in between. This approach ensures that the key press is recognized by the application under test:

  cy.get('body').trigger('keydown', { keyCode: 27 });
  cy.get('body').trigger('keyup', { keyCode: 27 });

The wait time can be adjusted based on the application’s requirements, but 200 milliseconds is often sufficient.

Alternative Approach

An alternative and potentially more robust approach is to use the cypress-real-events plugin. This plugin allows for more accurate simulation of native keypresses. By using the cy.realPress('Escape') command, you can simulate the ESCAPE key press effectively:


Note that this plugin is primarily supported in Chrome and may have limitations in other browsers.


Simulating key press events in Cypress can be achieved through various methods. Triggering keydown and keyup events with a wait time is a commonly used approach, while the cypress-real-events plugin offers a more native simulation option.

Enhancing Test Automation with Repeato

For those looking to streamline their test automation process further, consider using Repeato, a no-code test automation tool for iOS and Android. Repeato simplifies the creation, running, and maintenance of automated tests using computer vision and AI. It’s particularly fast to edit and run tests, making it an excellent choice for quality assurance.

Learn more about Repeato and how it can assist in your test automation needs by visiting our documentation or downloading the tool today.

Like this article? there’s more where that came from!