我目前正在嘗試調用一個函數,它調用一個http請求服務,然後在訂閱部分(調用一個函數並設置一個變量)做一些事情。到目前爲止,我的方法只是調用函數,我認爲請求服務將被自動調用,所以訂閱部分將被執行。但是,我覺得這不是它做的方式,因爲它不工作。Angular2 - 測試一個函數,調用一個http服務
我要測試的功能:
public trainBot() {
this.isTraining = true;
this.requestsService.trainModel(this.botId, false)
.subscribe(response => {
this.trainingStatus = this.trainingStatusMapping[response['status']];
this.pollTrainingStatus();
});
}
我的測試,到目前爲止(不工作)。
it('should poll the training status',() => {
spyOn(component, 'pollTrainingStatus').and.callThrough();
component.trainBot();
fixture.detectChanges();
expect(component.pollTrainingStatus).toHaveBeenCalled();
});
那麼,誰能告訴我如何測試.subscribe內部的部分(...部分
更新:
有人建議我加入的returnValue和異步我。測試他們仍然沒有工作,但現在看起來就像是:
it('should poll the training status', fakeAsync(() => {
component.trainBot();
spyOn(service, 'trainModel').and.returnValue(Observable.of({'status': 'training'}));
spyOn(component, 'pollTrainingStatus').and.callThrough();
fixture.detectChanges();
tick(1);
expect(service.trainModel).toHaveBeenCalled();
expect(component.pollTrainingStatus).toHaveBeenCalled();
}));
的錯誤是一樣的
您能分享您收到的錯誤或失敗測試的輸出結果嗎? – Kevin
@Kevin「期待間諜pollTrainingStatus被調用。」這意味着pollTrainingStatus()不叫 – threxx
看看這個問題:[angular2測試使用jasmine的訂閱方法](https://stackoverflow.com/questions/40080912/angular2-testing-using-jasmine-for-subscribe-method) 。讓我知道如果答案在那裏適合你。 – Kevin