测试-存根服务方法未定义 [英] Testing - Stubbing service method is undefined
问题描述
我已经用非常简单的代码编写了一个非常简单的测试,但是由于某些原因,存根服务方法未定义。当我使用Jasmine Spy时,它可以工作,但是可以完成如此简单的任务。有人可以解释为什么会这样(我删除导入语句只是为了减少代码):
I have written a very simple test on a very simple code but for some reason stub service method is undefined. When I use Jasmine Spy it works but for such a simple task. could someone please explain why is this happening (i have removed import statements just to reduce code):
businessarea-overview.component
businessarea-overview.component
@Component({
templateUrl: './businessarea-overview.component.html',
styleUrls: ['./businessarea-overview.component.css']
})
export class BusinessAreaOverviewComponent implements OnInit {
businessArea: BusinessArea;
businessAreaId: number;
errorMessage: string;
constructor(private businessAreaService: BusinessAreaService, private utilityService: UtilityService, private route: ActivatedRoute) {
this.businessArea = new BusinessArea();
this.route.params.subscribe(params => {
this.businessAreaId = +params['id'];
});
}
ngOnInit() {
if (!isNaN(this.businessAreaId)) {
this.businessAreaService.getBusinessAreaById(this.businessAreaId)
.subscribe(data => {
this.businessArea = data;
},
error => this.errorMessage = error);
}
}
}
businessarea-overview.spec.ts
businessarea-overview.spec.ts
describe('BusinessareaOverviewComponent', () => {
let component: BusinessAreaOverviewComponent;
let fixture: ComponentFixture<BusinessAreaOverviewComponent>;
beforeEach(async(() => {
const authServiceSpy = jasmine.createSpyObj("AuthService", ["authenticateUser"]);
authServiceSpy.authenticateUser.and.callFake(() => { return Observable.from([true]); });
//const businessAreaServiceSpy = jasmine.createSpyObj("BusinessAreaService", ["getBusinessAreaById"]);
//businessAreaServiceSpy.getBusinessAreaById.and.callFake(() => { return Observable.of(new BusinessArea()); });
TestBed.configureTestingModule({
declarations: [
BusinessAreaOverviewComponent
],
imports: [
GrowlModule,
FormsModule,
RadioButtonModule,
AutoCompleteModule,
DataTableModule,
MessagesModule
],
providers: [
{ provide: Http, useValue: httpServiceStub },
{ provide: AuthService, useValue: authServiceSpy },
{ provide: UtilityService, useValue: utilityServiceStub },
{ provide: ActivatedRoute, useValue: { params: Observable.of({id: 123})} },
{ provide: BusinessAreaService, useValue: businessAreaServiceStub }
]
}).compileComponents();
fixture = TestBed.createComponent(BusinessAreaOverviewComponent);
component = fixture.debugElement.componentInstance;
}));
it('should create the component', () => {
var businessAreaService = fixture.debugElement.injector.get(BusinessAreaService);
console.log(businessAreaService);
fixture.detectChanges();
expect(component).toBeTruthy();
});
});
export class httpServiceStub {
}
export class utilityServiceStub {
navigateTo(path: string, id: number, urlSegment){ }
}
export class businessAreaServiceStub{
getBusinessAreaById(id: number): Observable<BusinessArea> {
return Observable.of(new BusinessArea());
}
}
export class routerServiceStub {
}
测试类中的注释行已解决。当我执行console.log时,我可以清楚地看到调用
the commented lines in test class is the fix. when i do console.log I can clearly see the Stubbed service is injected when calling
this.businessAreaService.getBusinessAreaById
使用OnInit方法,但是 getBusinessAreaById 未定义并且不存在。
in OnInit method but getBusinessAreaById is undefined and not there.
我得到以下错误
TypeError:this.businessAreaService.getBusinessAreaById不是
函数
TypeError: this.businessAreaService.getBusinessAreaById is not a function
我知道这与 this 有关,但无法解决关于发生这种情况的原因。
I know it has to do with this but cant get my head around as to why this is happening.
business-area.service.ts
@Injectable()
export class BusinessAreaService {
constructor(private http: Http) {
}
saveBusinessArea(businessArea: BusinessArea): Observable<any> {
let body = JSON.stringify(businessArea);
let headers = new Headers(AppSettings.jsonContentTypeObject);
let options = new RequestOptions({ headers: headers });
if (businessArea && businessArea.id > 0)
return this.updateBusinessArea(businessArea.id, body, options);
return this.addBusinessArea(body, options);
}
private addBusinessArea(body: Object, options: Object): Observable<BusinessArea> {
return this.http.post(AppSettings.businessAreaEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private updateBusinessArea(id: number, body: Object, options: Object): Observable<BusinessArea> {
return this.http.put(AppSettings.businessAreaEndPoint + id, body, options)
.map(this.extractData)
.catch(this.handleError);
}
getBusinessAreaById(id: number): Observable<BusinessArea> {
return this.http.get(AppSettings.businessAreaEndPoint + id)
.map(this.extractData)
.catch(this.handleError);
}
getAllBusinessAreas(): Observable<BusinessArea[]> {
return this.http.get(AppSettings.businessAreaEndPoint)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(response: Response) {
let body = response.json().items || response.json();
return body || {};
}
private handleError(error: Response) {
console.log(error);
return Observable.throw(error || "500 internal server error");
}
}
推荐答案
更改 {提供:BusinessAreaService,useValue:businessAreaServiceStub}
到 {提供:BusinessAreaService,useClass:businessAreaServiceStub}
这篇关于测试-存根服务方法未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!