我正在測試一個注入了服務的Angular2組件。測試代碼低於但基本上:在Angular2測試中正確注入依賴關係
•SearchComponent的需要FightService在constrctor。
•構造函數調用引發HTTP請求的flightsService.getFlights()。 flightsService.getFlights()返回一個observable。
•構造訂閱了可觀察到的返回其填充allSummaryItems陣列。
不使用我的MockFlightService,它基本上是失敗說沒有供應商對於HTTP(這是在FlightService構造函數)。如果我將HttpModule添加到TestBed中的提供程序中,那麼它將關閉並觸發真正的Http請求。
我如何確保使用MockFlightService?這也將正確測試observable,即使發射一個真正的Http請求,我可以看到訂閱的方法沒有被調用?
感謝
class MockFlightsService {
public getFlights =() => {
return new Observable<any>(() => { return dummyData.json(); });
};
}
describe('SearchComponent Tests',() => {
let fixture: ComponentFixture<SearchComponent>;
let component: SearchComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SearchComponent],
imports: [RouterModule],
providers: [{ provide: FlightsService, useClass: MockFlightsService }]
});
fixture = TestBed.createComponent(SearchComponent);
fixture.detectChanges();
});
it('should render list', fakeAsync(() => {
fixture.whenStable();
component = fixture.componentInstance;
console.log(component.allSummaryItems); // this is empty, shouldn't be
}));
});
我使用角2.0.1。