I am trying to fire an Escape button press event in Angular unit tests.
    const event = document.createEvent('UIEvent');
    event.initUIEvent('keydown', true, true, window, 0);
    (<any>event).keyCode = 27;
    (<any>event).key = 'Escape';
    (<any>event).charCode = 27;
    document.body.dispatchEvent(event);
This does not work at all (event is never caught by listeners that do proper checking like event.which == 27).
What is the correct way to create such an event?
I tried this one too, in vain
    const event = new Event('keydown', {bubbles: true});
    event.initEvent('keydown', true, true);
    (<any>event).keyCode = 27;
    (<any>event).key = 'Escape';
    (<any>event).charCode = 27;
    document.body.dispatchEvent(event);
You only need to use a keyboard Event on document or on an element
     const event = new KeyboardEvent("keydown",{
     'key': 'Escape'
     });
     document.dispatchEvent(event);
You can test it with HostListener
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
    let keyPressed = event.keyCode;
    if (keyPressed === 27) {
       console.log('Escape!');
    }
}
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