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.
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:
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With