Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate long hold key press on cypress?

Tags:

cypress

I want to simulate a long key press of backquote key without selecting certain dom element, how can we achieve this using cypress? I have a functionality on my web app that will trigger when this key is pressed.

I have tried several code below and nothing works.

// 1st
cy.get('#sidepanel').trigger('keydown', { keycode: 192, release: false })

// 2nd
cy.get('body').type('`', { release: false })

// 3rd
cy.get('body').trigger('keydown', { keycode: 192, release: false })
cy.wait(15000)
cy.get('body').trigger('keyup', { keycode: 192, release: false })

I expect it will simulate the long and hold key press of backqoute, but it looks like the typing of backqoute only happens once and not hold.

like image 762
Inovramadani Avatar asked Mar 03 '23 18:03

Inovramadani


1 Answers

When you hold down a key in the browser, it actually ends up being many subsequent keydown/keypress events, followed by a keyup when you finally let go of the key.

You can verify this behavior by running this code in your browser:

['keydown','keypress','keyup'].map(e => {
  document.addEventListener(e, (p) => console.log(e, p))
})

Then, hold down a key and watch your console log to see what events are emitted. In Firefox, holding down the A key gives:

Screenshot of holding down A key


So, to do this with Cypress, you just need to emulate those events:

// holding down for 5 seconds
for (var i = 0; i < 100; i++) {
  cy.get('body').trigger('keydown', { keycode: 192, release: false })
  cy.get('body').trigger('keypress', { keycode: 192, release: false })
  cy.wait(50)
}
cy.get('body').trigger('keyup', { keycode: 192, release: false })
like image 116
Zach Bloomquist Avatar answered Mar 18 '23 10:03

Zach Bloomquist