Angular 如何测试ngOnInit内部的功能

Angular 如何测试ngOnInit内部的功能,angular,angular-test,Angular,Angular Test,我的组件类很简单。它从父组件获取一个输入,并根据该输入解析ngOnInit 我的组件类: 导出类TestComponent实现OnInit{ @Input()服务类型:字符串; serviceUrl:字符串; 恩戈尼尼特(){ this.findServiceType(); } findServiceType=()=>{ if(this.serviceType){ if(this.serviceType==='t1'){ this.serviceUrl=TestFileEnumConstant

我的组件类很简单。它从父组件获取一个输入,并根据该输入解析
ngOnInit

我的组件类:
导出类TestComponent实现OnInit{
@Input()服务类型:字符串;
serviceUrl:字符串;
恩戈尼尼特(){
this.findServiceType();
}
findServiceType=()=>{
if(this.serviceType){
if(this.serviceType==='t1'){
this.serviceUrl=TestFileEnumConstants.T1\u URL;
}else if(this.serviceType=='t2'){
this.serviceUrl=TestFileEnumConstants.T2\u URL;
}
}
}

}
您应该创建两个测试,而不是一个。第一个测试是
this.findServiceType()ngOnInit
上调用code>,然后执行第二个测试,单独测试
findServiceType
的功能

it('should correctly wire url based on type1', () => {
   component.serviceType = 'type1';
   component.findServiceType()

   expect(component.serviceUrl)
       .toBe(TestFileEnumConstants.T1_URL)
});

问题是因为
beforEach()
段中的
SpyOn
语句。由于mock函数不返回任何数据,因此返回值将一直处于未定义状态。问题陈述如下,我必须对
spyOn
陈述进行评论:

beforeach(()=>{
//spyOn(组件“findServiceType”);

});谢谢你提供的信息,我像你说的那样更新了我的测试用例。我所面临的真正问题是因为一个嘲弄性的语句-
spyOn(component,'findServiceType')。我已经更新了答案。