所以我尝试测试包含服务的组件方法。我将向您展示我为测试我的搜索方法所做的工作的一个例子。
这是包含搜索功能的组件:
search(idntDocTp:any,idntDocNo:any){
this.providersService.searchForSupportingStaffList(idntDocTp,idntDocNo).subscribe(
data => {
this.searchSupportingStaffData = data[0];
if (this.searchSupportingStaffData != null)
{
this.activeIndex = 1;
switch (this.searchSupportingStaffData.IdntType) {
case 'nID':
this.identificDocNumSymbol = 'NID';
break;
case 'passport':
this.identificDocNumSymbol = 'PAS';
break;
case 'arc':
this.identificDocNumSymbol = 'ARC';
break;
}
} else {
this.alertMessage = { severity: 'warn', summary: 'Warning Message', detail: 'No records were found. Please try again.' };
this.alertMessagesSrv.pushAlert(this.alertMessage);
}
});
这是我的服务
searchForSupportingStaffList(idntDocTp:any,idntDocNo:any): Observable<any> {
let costructUrl: string;
costructUrl = this.searchSupporting_staffUrl + '/?IdntType=' + idntDocTp + '&IdntNo=' + idntDocNo;
return this.http
.get(costructUrl,
{ headers: this.headers }
)
.map((res: any) => res.json().data);
}
这是我正在进行的测试,以检查我的服务是否有效(声明):
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
ProviderManagementModule,
// HttpModule,
BrowserAnimationsModule
],
//declarations: [ SupportingStaffComponent ],
providers: [
AlertMessagesService,
ProvidersService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory:(backend,options) => new Http(backend,options),
deps:[MockBackend,BaseRequestOptions]
}
]})
//Get the MockBackend
backend = TestBed.get(MockBackend);
//Returns a service with the MockBackend so we can test with dummy responses
service = TestBed.get(ProvidersService);
fixture = TestBed.createComponent(SupportingStaffComponent);
app = fixture.debugElement.componentInstance;});
这是实际的测试
it('return Search results and active index is changed', fakeAsync(() => {
let response = {
data: [
{id:1, name:'DummyName', IdntType:'nID', IdntNo:'991212', age:'27', start_date:'12 Sep 2017', end_date:'',contact_number:'99457845'}
]
}
backend.connections.subscribe(conn => {
conn.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(response) })));
});
service.searchForSupportingStaffList('dummyData','dummyData');
tick();
fixture.detectChanges();
expect(fixture.componentInstance.activeIndex).toEqual(1);
expect(fixture.componentInstance.searchSupportingStaffData.name).toMatch('DummyName')
expect(app.data.length).toBe(1);
}));
测试成功运行。我设置到服务功能的参数无关紧要,它仍然返回模拟数据。这就是为什么我很困惑。我认为我使用模拟数据提供服务,如果我使用错误的参数搜索服务将不会返回任何内容,但事实并非如此。有人解释我,如果我做错了吗?此外,即使从我的组件执行搜索方法而不是服务仍然获得相同的结果。我如何理解测试是否正常。
答案 0 :(得分:0)
这很好,因为你对响应进行了硬编码,我认为你这里没有做错任何事。测试服务是测试服务的外部api而不是返回数据。