Testing more complex behavior of user input involving keys with Cypress got me stuck. The app uses hotkeys to trigger operational modes and cannot afford to let random mouse/pointer events get fired whenever a key is pressed. One supposed scenario is
- hold down alt key
- draw a polygon
- release alt key
Using cy.type
results in the first two steps registering as a double click, performing an unwanted action. Release key action results in one more point (screen middle) being added to the polygon.
I tried many varians of type()
call, tried replacing it with trigger()
(did not even fire) with and without focus()
combination such as
cy.get(selector)
.trigger('keydown', { eventConstructor: 'KeyboardEvent', key: key, release: false })
.trigger('keypress', { eventConstructor: 'KeyboardEvent', key: key, release: false })
tried real cypress events plugin (which seem not to support key press without a release action).
How would you fire just a simple KeyboardEvent
event without all the mess around?
CodePudding user response:
If you want to have fine control over the events sent, use plain JS dispatchEvent()
cy.get(selector).then($el => {
$el[0].dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
})
The fact that trigger()
didn't work indicates you haven't identified the correct event or target, it should work the same way as dispatchEvent()
.
Since you're drawing, maybe you should be looking at mouse events instead of keyboard events (unless the app is supposed to draw using the keyboard).