我試圖在使用takeUntil()的Angular應用程序中正確取消訂閱Observable,但似乎打破了測試。使用takeUntil break單元測試取消訂閱Angular Observable
Chrome 58.0.3029 (Mac OS X 10.12.5) AppComponent should render title in a h1 tag FAILED
Failed: this.appService.getGuides(...).takeUntil is not a function
TypeError: this.appService.getGuides(...).takeUntil is not a function
at AppComponent.Array.concat.AppComponent.ngOnInit (webpack:///src/app/app.component.ts:28:7 <- src/test.ts:53764:14)
at checkAndUpdateDirectiveInline (webpack:///~/@angular/core/@angular/core.es5.js:10923:0 <- src/test.ts:11228:19)
這是代碼:
export class AppComponent implements OnDestroy, OnInit {
private ngUnsubscribe: Subject<void> = new Subject<void>();
title = 'app works!';
guides: Guide[];
constructor(private appService: AppService) {
}
ngOnInit(): void {
this.appService.getGuides()
.takeUntil(this.ngUnsubscribe)
.subscribe(
guides => this.setGuides(guides),
error => this.onError(error)
);
}
ngOnDestroy(): void {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
這是服務實現:
@Injectable()
export class AppService {
constructor(private http: Http) { }
getGuides(): Observable<Guide[]> {
return this.http.get(environment.apiUrl + '/guides')
.map(this.extractData);
}
private extractData(res) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
return res.json();
}
}
這是失敗的試驗:
class MockAppService extends AbstractMockObservableService {
getGuides() {
return this;
}
}
describe('AppComponent',() => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent]
});
TestBed.overrideComponent(AppComponent, {
set: {
providers: [
{ provide: AppService, useClass: MockAppService }
]
}
});
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('app works!');
}));
post this.appService.getGuides()code? – CharanRoot
我剛剛添加了服務實現以及我在測試中使用的模擬服務,在[this]之後(https://stackoverflow.com/questions/39960146/angular-2-testing-error-case-with-observables在服務/ 39960878#39960878) – Cedric