Snippet: Simulating Escape Key for Unit Tests in JS

Just a little code snippet I had to work to get right: simulating an escape key on the document element:

function hitEscapeKey() {
// Browser bug: can't use keyboard events, so we do it this way.
// See https://tinyurl.com/mholrhv
const escapeKey = document.createEvent("Events");
escapeKey.initEvent("keydown", true, true);
escapeKey.keyCode = 27;
escapeKey.which = 27;
document.dispatchEvent(escapeKey);
}
Like what you read? Give Danny Thielman a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.