On a focused button, when user hits "Space" or "Enter" key, browser will synthesise a click event on top of those keyboard events.
I tried to simulate keydown, keyup of a "Space" key on a focused button, but could not find the way to let browser synthesise a click event.
document.activeElement.dispatchEvent(new KeyboardEvent('keydown',{which: 32, keyCode: 32, key: ' ', code: 'Space'}));
document.activeElement.dispatchEvent(new KeyboardEvent('keyup',{which: 32, keyCode: 32, key: ' ', code: 'Space'}));
Here is what I got so far https://jsfiddle.net/s21f9pg7/
const btn = document.querySelector('#btn');
btn.onclick = function(e) {
console.log('click', e.type);
}
btn.onkeydown = function(e) {
console.log('keydown', e.type);
}
btn.onkeypress = function(e) {
console.log('keypress', e.type);
}
btn.onkeyup = function(e) {
console.log('keyup', e.type);
}
setTimeout(() => {
btn.focus();
document.activeElement.dispatchEvent(new KeyboardEvent('keydown', {
which: 32,
keyCode: 32,
key: ' ',
code: 'Space'
}));
/* document.activeElement.dispatchEvent(new KeyboardEvent('keypress',{which: 32, keyCode: 32, key: ' ', code: 'Space'})); */
setTimeout(() => {
document.activeElement.dispatchEvent(new KeyboardEvent('keyup', {
which: 32,
keyCode: 32,
key: ' ',
code: 'Space'
}));
}, 200);
}, 200)
<button id="btn">click</button>
This snippet issue a keydown and a keyup on a focused button, no click event was fired. However, if you manually hit space key, there will be a click event along with keyboard events.
I am trying to find a way to do unit testing on focused button. Thanks for help!