作者:mobiledu2502855247 | 来源:互联网 | 2022-12-01 18:17
我目前正在使用ngBootstrap的自动完成机制(typeahead).现在我想要对输入事件的每个序列调用一个方法进行单元测试.我的测试用例的错误目前是:Cannot read property 'pipe' of undefined
HTML:
零件:
public ngOnInit() {
this.search = (text$: Observable) =>
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 = {uid: 'test', username: 'mleko', location: null, description: null};
const 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();
}));
有人可以帮我嘲笑这个.搜索得当吗?
编辑
通过@dmcgrandle的精彩建议,我不需要渲染HTML并模拟输入事件,以检查输入事件是否正常工作.我宁愿做一个Observable,它会发出值并将它分配给函数.一种方法是:
it('should call spy on city search', fakeAsync(() => {
const 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();
}));
但问题仍然是,component.search
不要打电话给间谍.在switchMap
运算符的搜索函数中,我添加了一个console.log
以查看函数是否发出了值.但事实并非如此.也许有人可以为我的问题提供stackblitz.:)