I am currently facing a challenge while attempting to test a function that invokes an HTTP request service and then performs actions in the subscribe section (calls another function and sets a variable). Initially, I tried calling the function directly assuming that the request service would be triggered automatically, leading to the execution of the subscribe section. However, it seems this approach is not yielding the expected results.
The specific function I intend to test is as follows:
public trainBot() {
this.isTraining = true;
this.requestsService.trainModel(this.botId, false)
.subscribe(response => {
this.trainingStatus = this.trainingStatusMapping[response['status']];
this.pollTrainingStatus();
});
}
This is what my current test looks like (but it is not functioning as desired).
it('should poll the training status', () => {
spyOn(component, 'pollTrainingStatus').and.callThrough();
component.trainBot();
fixture.detectChanges();
expect(component.pollTrainingStatus).toHaveBeenCalled();
});
Therefore, I am seeking guidance on how to effectively test the portion inside the .subscribe(...) block.
Update:
Following a suggestion, I have updated my test with returnValue and async but unfortunately, it is still not producing the expected output. Here is the revised version:
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();
}));
Despite these changes, the error remains consistent.