我有一个模拟服务
export class DataServiceStub {
numbers$ = of([1,2,3,4,5,6]).pipe(
switchMap((data: number[]) => {
if (this._error) {
return throwError(this._error);
}
return of(data);
});
private _error: string;
setError(msg: string) {
this._error = msg;
}
}
我将在使用该服务的组件中测试错误案例
it('should show an error message', async(() => {
const errorMessage = `Fetch data error`;
testDataService.setError(errorMessage);
// spyOnProperty(dataStub, 'numbers$').and.returnValue(throwError(errorMessage));
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('.error').textContent).toContain(errorMessage);
}));
组件看起来像这样
@Component({
selector: 'app-root',
template: `
<div *ngFor="let num of numbers$ | async">...</div>
<div *ngIf="error$ | async as error" class="error">{{error}}</div>
`
})
export class AppComponent {
numbers$ = this._dataService.numbers$;
error$ = this._dataService.numbers$.pipe(
filter(() => false),
catchError((error: string) => of(error))
);
}
我怎样才能避免这样的结果?