After diving headfirst into coding with RxJs without much prior knowledge, I found myself copying and pasting code snippets, tweaking them to fit my needs, only to hit roadblocks when trying to test the code...
Let me share the entire component for context:
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operator/map';
import { debounceTime } from 'rxjs/operator/debounceTime';
import { distinctUntilChanged } from 'rxjs/operator/distinctUntilChanged';
import { _catch } from 'rxjs/operator/catch';
import { _do } from 'rxjs/operator/do';
import { switchMap } from 'rxjs/operator/switchMap';
import { of } from 'rxjs/observable/of';
import { ApiService } from '../../services/api/api.service';
import { ISearchSuggestion } from './search.interface';
@Component({
selector: 'msm-search',
templateUrl: './search.component.html'
})
export class SearchComponent {
public model: string;
private _isSearching = false;
get isSearching() { return this._isSearching; }
constructor(
private router: Router,
private apiService: ApiService
) {}
search = (text$: Observable<string>) => {
return _do.call(
switchMap.call(
_do.call(
distinctUntilChanged.call(
debounceTime.call(text$, 300)),
this.enableSearching.bind(this)
),
this.performSearch.bind(this)
),
() => {
this._isSearching = false;
}
);
}
private enableSearching(term: string) {
if (term.length > 2) {
this._isSearching = true;
}
}
private performSearch(term: string) {
if (term.length > 2) {
return _catch.call(
_do.call(this.apiService.getSearchSuggestions(term)),
() => of.call([])
)
}
}
}
I'm struggling to test the search functionality using setTimeout and jasmine.tick(), here's a snippet of my attempt:
it('Should get suggestions if search term is longer than 2 characters', (done) => {
const searchTerm = '123test';
const stringObservable = new Observable<string>(observer => {
setTimeout(() => {
observer.next(searchTerm);
observer.complete();
}, 50);
});
spyOn(apiService, 'getSearchSuggestions');
component.search(stringObservable);
setTimeout(() => {
expect(apiService.getSearchSuggestions).toHaveBeenCalledWith(searchTerm);
done();
}, 500);
});
Any insights on what might be going wrong in my testing approach?