2016-09-20 77 views
0

我需要按下按鍵時觸發的單元測試功能。如何在茉莉花中模擬按鍵單元測試

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; 
    } 
    } 

如何模擬按鍵來滿足第一個條件,例如?

+0

http://stackoverflow.com/questions/961532/firing-a-keyboard-event-in-javascript – Randy

回答

0

下面的示例代碼顯示瞭如何創建,觸發和攔截事件。

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);