我有一个响应式表单,在提交过程中,我向API发送了一个http请求,并基于其结果(成功/失败),我正在致电我的警报服务以显示警报:
public submit(formValues): void {
this.generationProjectService
.add(
new CreateGenerationProjectRequest(
formValues.selectedIndustry,
formValues.selectedEdition,
formValues.selectedDate,
formValues.selectedTemplate,
formValues.selectedImportant
)
)
.subscribe(
newGenerationProject => {
this.domainEventService.onNewGenerationProject.emit(newGenerationProject);
this.alertService.success('Project was successfully added to Overnight Generation');
},
() => {
this.alertService.error('Something went wrong');
}
);
this.close();
}
这很好用,我想测试一下,但是我很难理解。
fit('should notify failed project addition', () => {
spyOn(generationProjectService, 'add').and.throwError('up');
const errorSpy = spyOn(alertService, 'error').and.callThrough();
component.submit({});
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(errorSpy).toHaveBeenCalledTimes(1);
});
});
但这不起作用。
要使此功能正常工作,我必须在测试用例中进行哪些更改。还是我可以更改代码以使其更具可测试性?
答案 0 :(得分:2)
我认为是因为您的间谍正在抛出Javascript错误而不是Observable发出错误,请尝试这种方式:
import { throwError } from 'rxjs';
spyOn(generationProjectService, 'add').and.returnValue(throwError('This is an error!'));