所以我尝试测试包含服务的组件方法。我将向您展示一个示例,说明我为测试我的搜索方法所做的工作。
这是我包含搜索功能的组件:
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);
}));
测试成功运行。我为服务函数设置什么参数并不重要,它仍然返回模拟数据。这就是为什么我很困惑。我以为我为服务提供了模拟数据,如果我使用错误的参数进行搜索,服务将不会返回任何内容,但事实并非如此。如果我做错了,有人可以解释一下吗?此外,即使从我的组件执行搜索方法,服务仍然会得到相同的结果。我如何真正理解测试是否正常。