【发布时间】:2018-01-10 04:10:25
【问题描述】:
我目前正在尝试测试一个调用 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 和 async。他们仍然不工作,但现在看起来像这样:
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 “预计间谍 pollTrainingStatus 已被调用。”这意味着 pollTrainingStatus() 没有被调用
-
看看这个问题:angular2 testing using jasmine for subscribe method。让我知道那里的答案是否适合您。
-
所以我尝试添加 '.and.returnValue({ subscribe: () => {} })' 部分,但这并没有改变任何东西
-
我刚刚意识到,你不需要监视
this.requestsService.trainModel吗?
标签: angular unit-testing typescript