11

Working on webpage test automation with Cypress atm. Ran into a problem.

  • I need to simulate a pressing of the ESCAPE key from a user.

Cypress has its own type() method, but it is required to chain off a DOM element, e.g. it has to be implemented this way:

cy.get(element).type('{esc}');

I want to simulate a simple key press of ESCAPE without involving any DOM element. Does anyone know how to do it?

I have tried

cy.get('body').type('{esc}');

which does not work.

Update:

I tried

cy.get('body').trigger('keydown', { keyCode: 27, which: 27 });//27 is the keycode for the escape key

Did not work either. I guess there is a mis-alignment between my expectation and Cypress specification.

  • What I want to do is a simple key press from keyboard while Cypress has its type() to type into an element, they could be two different things.

3 Answers 3

6

Found an answer:

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

The amount of time cy.wait() waits is arbitrary. It depends on the application under test; but 200 mS seems to be working for me too.

3
  • As of april 2022 this no longer works. I think a jQuery solution would be more appropriate as explained by Gleb himself in a Youtube video.
    – thednp
    Apr 14 at 15:44
  • @thednp Do you have a link to that YouTube video? Or some more detail to help me search for it? Jul 13 at 22:12
  • @MatthewWalker I can't remember the exact video, you might look for Gleb Bahmutov's channel on YT and search through his videos. You can also have a look at my color-picker Cypress tests on github, I managed to get it to work eventually, despite me saying it doesn't. The problem is always related to sync/async assertions, you might want to see what you do (ACTION and CONTEXT => assertion) before triggering events, assertions & actions can overlap, so you can also set separate it() for event assertions. Good luck.
    – thednp
    Jul 14 at 5:04
6

The recommended command is:

cy.get('#someId').type('{esc}');

I'm using this to disclose pop-ups and where it makes sense to use ESCape as a User.

Cypress version: 8.3.0

0

I was able to simulate native keypresses by utilizing the following repo: https://github.com/dmtrKovalenko/cypress-real-events

With the included cy.realPress('Escape') command it should work like a charm for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.