2017-12-06 4 views
0

http 호출을하는 서비스로 모의하려고합니다. 나는 가짜 데이터를 가짜 데이터로 제공하고 테스트에서이 데이터를 확인하고 싶습니다.spyOn 및 returnValue에 데이터 전달

내 설정입니다.

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} });

답변

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'); 
}); 
+0

트릭을 수행했습니다. 고맙습니다! – abyrne85