我有一个调用服务类进行某些操作的组件。服务类使用httpClient调用永恒的api。我正在尝试如下测试组件:
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [SomeService],
}).compileComponents();
service = TestBed.get(SomeService);
}));
fit('should', async () => {
fixture.detectChanges();
const fakeHttpPromise = {
success: function () { }
};
spyOn(service, 'save').and.callFake(function () {
return fakeHttpPromise;
});
const textbox1 = fixture.debugElement.query(By.css('input[formControlName=control1]'));
textbox1.nativeElement.value = 'value';
const textbox2 = fixture.debugElement.query(By.css('input[formControlName=constrol2]'));
textbox2.nativeElement.value = 'value';
// here i Create model object using textbox1 and textbox2 value
// This should not call actual service
component.Save(model);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(service.save).toHaveBeenCalled();
});
});
这是保存单击的组件:
Save(model: any) {
this.Service.save(model)
.then((res) => {
}
}
问题:当间谍返回假承诺时,为什么要调用实际服务?实际的服务使用的是httpclient,我不想实际调用它,而只是返回一个虚假的承诺。
答案 0 :(得分:0)
这是我解决此问题的方法:
1)更改了“保存”单击以从组件中的本地方法调用服务:
Save(model: any) {
this.btnsave(model).then((res) => {
}
}
btnsave(model){
return this.Service.save(model);
}
2)将测试更改为:
fit('should', async () => {
fixture.detectChanges();
const fakeHttpPromise = Promise.resolve();
// spy on components method
spyOn(component, 'btnsave').and.returnvalue(fakeHttpPromise);
const textbox1 = fixture.debugElement.query(By.css('input[formControlName=control1]'));
textbox1.nativeElement.value = 'value';
const textbox2 = fixture.debugElement.query(By.css('input[formControlName=constrol2]'));
textbox2.nativeElement.value = 'value';
// here i Create model object using textbox1 and textbox2 value
// This should not call actual service
component.Save(model);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
// check on component method
expect(component.btnsave).toHaveBeenCalled();
});
});