How to check if my element was concentrated in unit test in angular 4?

I have the following function for unit test. I took an element, which is a text field with a child view in the component, and in testing I need to check whether my text field was focused or not after setTimeout().

 @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();
        });
    }));
+6
source share
3 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(nomeInput);

Louis

+4
source

Luis Abreu's answer worked for me, because not only did I want to spy so that the focus method was called, but so that the focus was set to the desired element in the view. Here is an example:

describe('Email input focus', () => {
  beforeEach(() => {
    spyOn(comp.emailField.nativeElement, 'focus');
    comp.ngAfterViewInit();
  });

  it('Should call the focus event', () => {
    expect(comp.emailField.nativeElement.focus).toHaveBeenCalled();
  });

  it('Should be focused on the view', () => {
    fixture.detectChanges();
    const emailInput = de.query(By.css('#email')).nativeElement;
    const focusedElement = de.query(By.css(':focus')).nativeElement;
    expect(focusedElement).toBe(emailInput);
  });
});
+3

const input = fixture.nativeElement.querySelector('#your-input-id:focus');
expect(input).toBeTruthy();
0

Source: https://habr.com/ru/post/1679874/


All Articles