简体   繁体   中英

how to simulate keypress for unit testing in jasmine

I need to unit test function that is triggered when key pressed.

public onKeyDown(event: KeyboardEvent): void {
    if (event.ctrlKey && event.keyCode === 38) {
      console.log('increase');
    }
    if (event.ctrlKey && event.keyCode === 40) {
      console.log('decrease');
    }

    /* Prevent entering characters */
    if (event.keyCode >= 65 && event.keyCode <= 90) {
      return;
    }
  }

How can I simulate keypress to satisfy the fist condition, for example?

The example code below shows how an event is created, triggered, and intercepted.

var keyPressed = null;

function keyPress(key) {
  var event = document.createEvent('Event');
  event.keyCode = key;
  event.initEvent('keydown');
  document.dispatchEvent(event);
}

document.addEventListener('keydown', function(e){
   keyPressed = e.keyCode;
});

keyPress(37)
alert(keyPressed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM