I am currently using a autocomplete mechanism (typeahead) of ngBootstrap. Now I want to unit test if a method is called on every sequence of an input event. The error on my test case is currently: Cannot read property 'pipe' of undefined
Html:
<input id="locationEdit" type="text" class="form-control"
[(ngModel)]="user.location" name="location [ngbTypeahead]="search"/>
Component:
public ngOnInit() {
this.search = (text$: Observable<string>) =>
text$.pipe(
tap(() => {
this.isSearching = true;
this.searchFailed = false;
}),
debounceTime(750),
distinctUntilChanged(),
switchMap(term =>
this.cityService.getLocation(term).pipe(
tap((response) => {
this.searchFailed = response.length === 0;
this.isSearching = false;
})))
);
}
spec.ts
it('should call spy on city search', fakeAsync(() => {
component.user = <User>{uid: 'test', username: 'mleko', location: null, description: null};
const spy = (<jasmine.Spy>cityStub.getLocation).and.returnValue(of['München Bayern']);
fixture.detectChanges();
const compiled: DebugElement = fixture.debugElement.query(By.css('#locationEdit'));
compiled.nativeElement.value = 'München';
compiled.nativeElement.dispatchEvent(new Event('input'));
tick(1000);
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
}));
Can someone help me to mock this.search properly?
Edit
By the awesome suggestion of @dmcgrandle I don't need to render the HTML and simulate an input-event, to check if the typeahead is working. I rather should make an Observable, which emits values and assigns it to the function. One approach is:
it('should call spy on city search', fakeAsync(() => {
const spy = (<jasmine.Spy>cityStub.getLocation).and.returnValue(of['München Bayern']);
component.ngOnInit();
const textMock = of(['M', 'Mün', 'München']).pipe(flatMap(index => index));
component.search(textMock);
tick();
expect(spy).toHaveBeenCalled();
}));
But the problem still is, component.search
does not call the spy. Within the search function in the switchMap
operator I added a console.log
to see if value are emitted from the function. But that is not the case.
text$.pipe(
put a debug point or a console.log and check what is the value come there – ManutiusspyOn(component, 'search').and.returnValue(of('some string'));
– Cavefish