2017-12-06 13 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

関連する問題