2016-09-30 136 views
2

我正在測試一個注入了服務的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。

回答

2

我MockFlightService沒有被使用,它基本上無法說是沒有提供對HTTP(這是在FlightService構造函數)

隨着你是顯示的配置,我可以的唯一途徑看到這種情況發生,如果你在@Component.providers列出服務。這將覆蓋任何模塊級別的提供者。因爲我完全忘記了我已經在那裏,所以我正在把頭髮扯出一整天。

如果該服務應該是應用程序範圍的提供者,那麼將其從@Component.providers中取出並將其添加到@NgModule.providers

如果你的目標是限制服務組件級,那麼你應該做的,而不是爲覆蓋供應商進行了測試組件,而不是添加提供商到測試模塊中。

TestBed.overrideComponent(SearchComponent, { 
    set: { 
    providers: [ 
     { provide: FlightsService, useClass: MockFlightsService } 
    ] 
    } 
}); 

這應該在創建組件之前完成。

你可以在Overriding Test Providers看到更多。

其他的事情不相關的錯誤。

  • 您使用RouterModule。對於測試您應該使用RouterTestingModule,如上所述here
  • whenStable返回承諾。只是叫它,並不保護你。你需要訂閱它,然後在那裏做你的東西。

    whenStable().then(() => { 
        // Do stuff here. This is when the async tasks are completed. 
    }) 
    
  • 退房this post,對於如何嘲笑Http,如果你需要,那麼你是不是做一個測試過程中的XHR請求的例子。