Unable to simulate keypress event in Angular 2 unit test (Jasmine)

后端 未结 3 1497
粉色の甜心
粉色の甜心 2020-12-30 22:20

I am using a directive to get the data from input used as a filter text.

here is my hostlistener in the directive:

@HostListener(\'input\', [\'$event         


        
相关标签:
3条回答
  • 2020-12-30 22:54

    I've had some trouble simulating a keypress in a unit test also. But came across an answer by Seyed Jalal Hosseini. It might be what you're after.

    If you're attempting to simulate a keypress you can trigger an event by calling dispatchEvent(new Event('keypress')); on the element.

    Here is the answer I'm referring to which gives more detail : https://stackoverflow.com/a/37956877/4081730

    If you want to set the key that was pressed, this can be done also.

    const event = new KeyboardEvent("keypress",{
        "key": "Enter"
    });
    el.dispatchEvent(event);
    

    Further information I've just come across: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

    0 讨论(0)
  • 2020-12-30 23:07

    it('should trigger a TAB keypress event on an element', () => { const tabKeypress = new KeyboardEvent('keypress', { // @ts-ignore keyCode: 9, // Tab Key cancelable: true }); const myTableEle = debugEle.nativeElement.querySelector('.your-element'); myTableEle.dispatchEvent(tabKeypress); fixture.detectChanges(); });

    // @ts-ignore :- is to remove TS warning because keyCode is deprecated. Its not needed in case you want to set "key" property of KeyboardEvent.

    0 讨论(0)
  • 2020-12-30 23:11

    If you wish to use a key code (or "which"), you can do this:

    // @HostListener('document:keypress')
    
    const escapeEvent: any = document.createEvent('CustomEvent');
    escapeEvent.which = 27;
    escapeEvent.initEvent('keypress', true, true);
    document.dispatchEvent(escapeEvent);
    
    0 讨论(0)
提交回复
热议问题