【发布时间】:2019-03-25 16:00:48
【问题描述】:
我目前正在使用 ngBootstrap 的自动完成机制(预先输入)。现在我想对输入事件的每个序列是否调用方法进行单元测试。我的测试用例的错误目前是:Cannot read property 'pipe' of undefined
HTML:
<input id="locationEdit" type="text" class="form-control"
[(ngModel)]="user.location" name="location [ngbTypeahead]="search"/>
组件:
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();
}));
有人可以帮我正确地模拟 this.search 吗?
编辑
通过@dmcgrandle 的精彩建议,我不需要渲染 HTML 并模拟输入事件来检查预输入是否正常工作。我宁愿制作一个 Observable,它会发出值并将其分配给函数。一种方法是:
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();
}));
但问题仍然是,component.search 没有调用间谍。在 switchMap 运算符的搜索函数中,我添加了一个 console.log 以查看函数是否发出了值。但事实并非如此。
【问题讨论】:
-
错误来自
text$.pipe(放置调试点或console.log 并检查那里的值是什么 -
尝试添加
spyOn(component, 'search').and.returnValue(of('some string')); -
@HDJEMAI 我已经尝试过了,但它让我搜索方法在该组件上不存在..
标签: angular rxjs karma-jasmine ng-bootstrap angular-test