Angular how to unit test (focused) element / arrow behaviour?

179 Views Asked by At

I have implemented arrow-behaviour for setting the next/previous selected element in some list. It should only react when not in a INPUT-type element, so I check the document.activeElement

What is the proper way to test this using jasmine/spies?

private isActiveElementAnInput(): boolean {
    let activeElement: Element | null = this.getActiveElement();
    const inputs: string[] = ['input', 'select', 'button', 'textarea'];
    return (activeElement && inputs.indexOf(activeElement.tagName.toLowerCase()) !== -1) || false;
}

private getActiveElement(): Element | null {
    return document.activeElement;
}

@HostListener('document:keydown.arrowright')
public arrowRight(): void {
    if (!this.isActiveElementAnInput()) {
        this.nextItem();
    }
}
1

There are 1 best solutions below

0
Rob Audenaerde On

Ok this is how I ended up doing it, I set a real active element.

let inputElement: HTMLInputElement = combinedFixture.debugElement.query((By.css('input'))).nativeElement;
inputElement.focus();

I wrapped my component that needed testing a component that has an <ng-content>.

The outer component has a template that contains some extra HTML elements (like input, button etc).