How do I check if my element has been focused in a unit test in angular 4?

Pranjal picture Pranjal · Jun 22, 2017 · Viewed 11.2k times · Source

I have following function to unit test. I have taken element which is text box with view child in component and in testing I need to test whether my text box got focused or not after setTimeout() was called.

 @ViewChild('searchInput') searchInput: ElementRef;
function A(show) {
        const self = this;
        if (show) {
            this.xyz= true;
            setTimeout(function () {
                self.searchInput.nativeElement.focus();
            }, 0);
        } else {
            self.xyz= false;
            self.abc = '';
        }
    }

Here is my test case that I am trying:

it('textbox get focus toggleSearch', async(() => {
        let el: DebugElement;

        component.toggleSearch(true);
        el = fixture.debugElement.query(By.css('#search-input-theme'));
        let native: HTMLElement = el.nativeElement;
        spyOn(native,'focus');
        fixture.whenStable().then(() => {
            expect(native.focus).toHaveBeenCalled();
        });
    }));

Answer

Luis Abreu picture Luis Abreu · Jul 11, 2017

maybe something like this:

const input = de.query(By.css("your_field_selector")).nativeElement;
const focusElement = de.query(By.css(":focus")).nativeElement;
expect(focusElement).toBe(input);

Luis