How to generate an Escape key press in pure Typescript (w/o JQuery)

Viewed 8008

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);
1 Answers
Related