jquery (or pure js) simulate enter key pressed for testing

JavascriptJqueryTestingMocking

Javascript Problem Overview


What the best way to simulate the user pressing "enter"? $(element).keypress() doesn't seem to allow me to pass in the actual key that was pressed.

This is for unit testing.

Javascript Solutions


Solution 1 - Javascript

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

Solution 2 - Javascript

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmorgancodesView Question on Stackoverflow
Solution 1 - JavascriptredsquareView Answer on Stackoverflow
Solution 2 - JavascriptFabien SaView Answer on Stackoverflow