【发布时间】:2018-07-31 03:47:58
【问题描述】:
我有一个调用服务类来执行某些操作的组件。服务类使用 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,我不想实际调用它,而只是返回一个虚假的承诺。
【问题讨论】:
-
你也可以添加组件代码吗?
-
在这里删除fixture.detectChanges:fit('should', async () => { fixture.detectChanges();
-
删除 fixture.dectectChanges() 没有帮助。有任何想法吗 ?组件保存点击已经提供。请看一看。
标签: angular karma-jasmine