Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
        });
    }));
like image 371
Pranjal Avatar asked Jun 22 '17 09:06

Pranjal


People also ask

How do you know if an element is focused Angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.

How can we get an instance of the component to be tested?

You should configure a testing module before each test, using the TestBed . Here you can declare you component to test, and any providers it needs. Then you create the component using the TestBed also.

How would you spy on any element in Angular?

var mockEl = { on: angular. noop }; spyOn(angular, 'element'). andReturn(mockEl); spyOn(mockEl, 'on');


1 Answers

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

like image 91
Luis Abreu Avatar answered Oct 20 '22 14:10

Luis Abreu