我试图模拟对进行http呼叫的服务的调用。我想在模拟中提供假数据,并在我的测试中检查它。
这是我的设置。
beforeEach(() => {
fixture = TestBed.createComponent(MhSearchFormComponent);
component = fixture.componentInstance;
component.propertyCount = 0;
spyOn(component._searchService, 'getCount').and.returnValue({ subscribe: () => {} });
fixture.detectChanges();
});
我想在间谍的回归中重新分配propertyCount
值。
这是我的测试:
it('should get a count on load', () => {
expect(component.propertyCount).toBe('1000');
});
我已经尝试过了,但这显然是错误的
spyOn(component._searchService, 'getCount').and.returnValue({ subscribe: () => {'Count':1000} });
答案 0 :(得分:1)
我不知道你的组件/服务是怎样的。请尝试以下示例。如果您遇到任何问题,请发布组件和服务模板。
beforeEach(() => {
fixture = TestBed.createComponent(MhSearchFormComponent);
component = fixture.componentInstance;
component.propertyCount = 0;
// To get injected Service Instance from Component.
const searchService = fixture.debugElement.injector.get(SearchService);
// Observable.of('1000') will ensure the subscribe method and its handling
// And the subscriber will get '1000' as argument.
spyOn(searchService, 'getCount').and.returnValue(Observable.of('1000'));
fixture.detectChanges();
});
it('should get a count on load', () => {
expect(component.propertyCount).toBe('1000');
});