在Angular2测试中正确注入依赖项
我正在努力测试一个注入了服务的Angular2组件。测试代码如下,但基本上: •SearchComponent在Constructor中提供战斗服务 •构造函数调用flightsService.getFlights(),该函数发出HTTP请求。getFlights()返回一个可观察的 •构造函数订阅填充allSummaryItems数组的可观察返回值 我的MockFlightService没有被使用,它基本上失败了,因为没有Http的提供程序(在FlightService构造函数中)。如果我将HttpModule添加到TestBed中的提供者中,那么它将关闭并触发真正的Http请求 如何确保我正在使用MockFlightService?即使在触发一个真正的Http请求时,我也能看到订阅的方法没有被调用,这也能正确地测试可观察性吗 谢谢在Angular2测试中正确注入依赖项,angular,jasmine,karma-jasmine,angular2-testing,Angular,Jasmine,Karma Jasmine,Angular2 Testing,我正在努力测试一个注入了服务的Angular2组件。测试代码如下,但基本上: •SearchComponent在Constructor中提供战斗服务 •构造函数调用flightsService.getFlights(),该函数发出HTTP请求。getFlights()返回一个可观察的 •构造函数订阅填充allSummaryItems数组的可观察返回值 我的MockFlightService没有被使用,它基本上失败了,因为没有Http的提供程序(在FlightService构造函数中)。如果我将H
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
}));
});
类mockflights服务{
公共航班=()=>{
返回新的可观察对象(()=>{return dummyData.json();});
};
}
描述('SearchComponent Tests',()=>{
let夹具:组件夹具;
let组件:SearchComponent;
在每个之前(()=>{
TestBed.configureTestingModule({
声明:[SearchComponent],
导入:[路由模块],
提供程序:[{provide:FlightsService,useClass:MockFlightsService}]
});
fixture=TestBed.createComponent(SearchComponent);
fixture.detectChanges();
});
它('should render list',fakeAsync(()=>{
fixture.whenStable();
组件=fixture.componentInstance;
console.log(component.allSummaryItems);//这是空的,不应为空
}));
});
我用的是Angular 2.0.1
我的MockFlightService没有被使用,它基本上失败了,说没有Http的提供者(它在FlightService构造函数中)
根据您显示的配置,我能看到这种情况发生的唯一方法是在@Component.providers
中列出服务。这将覆盖任何模块级提供程序。我把头发扯了一整天,因为我完全忘了我在那里
如果服务应该是应用程序范围的提供者,则将其从@Component.providers
中取出并添加到@NgModule.providers
如果您的目标是将服务限制在组件级别,那么您应该做的是覆盖测试组件中的提供程序,而不是将提供程序添加到测试模块中
TestBed.overrideComponent(SearchComponent, {
set: {
providers: [
{ provide: FlightsService, useClass: MockFlightsService }
]
}
});
这应该在创建组件之前完成
你可以在这里看到更多
与错误无关的其他事项
- 使用
。如前所述,对于测试,您应该使用RouterModule
RouterTestingModule
返回承诺。只是打电话,并不能保护你。你需要订阅它,然后在那里做你的事情whenStable
whenStable().then(() => { // Do stuff here. This is when the async tasks are completed. })
- 如果需要,请查看如何模拟
,以便在测试期间不发出XHR请求Http