我在一个非常简单的代码上编写了一个非常简单的测试,但由于某种原因,存根服务方法是未定义的。当我使用Jasmine Spy时,它可以工作,但是这样一个简单的任务。有人可以解释为什么会发生这种情况(我已经删除了导入语句只是为了减少代码):
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
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时,我可以清楚地看到在调用
时注入了Stubbed服务this.businessAreaService.getBusinessAreaById
在OnInit方法中但 getBusinessAreaById 未定义且不存在。
我得到以下错误
TypeError:this.businessAreaService.getBusinessAreaById不是 功能
我知道这与 this 有关,但无法理解为什么会发生这种情况。
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");
}
}
答案 0 :(得分:0)
将{ provide: BusinessAreaService, useValue: businessAreaServiceStub }
更改为{ provide: BusinessAreaService, useClass: businessAreaServiceStub }