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();
});
}));
hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.
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.
var mockEl = { on: angular. noop }; spyOn(angular, 'element'). andReturn(mockEl); spyOn(mockEl, 'on');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With