Angular 角度测试仅适用于模拟服务类,而不适用于值
我有以下的角度(4)组件测试。组件中有一行this.jobService.subscribeEvent('thisline')Angular 角度测试仅适用于模拟服务类,而不适用于值,angular,unit-testing,typescript,Angular,Unit Testing,Typescript,我有以下的角度(4)组件测试。组件中有一行this.jobService.subscribeEvent('thisline') 类MockJobService{ 公共subscribeEvent(行:字符串):可观察{ 返回({action:'dwnTime'}})的可观察.of } } 描述('NotificationComponent',()=>{ let组件:NotificationComponent; let夹具:组件夹具; 让mockJobService=newmockjobservi
类MockJobService{
公共subscribeEvent(行:字符串):可观察{
返回({action:'dwnTime'}})的可观察.of
}
}
描述('NotificationComponent',()=>{
let组件:NotificationComponent;
let夹具:组件夹具;
让mockJobService=newmockjobservice();
beforeach(异步(()=>{
TestBed.configureTestingModule({
声明:[NotificationComponent],
供应商:[
{provide:JobService,useValue:mockJobService}
]
}).compileComponents();
}));
当我运行此测试时,会出现以下错误:
TypeError:无法读取未定义的属性“subscribe”
但是,如果我将测试更改为包含以下行:
{provide:JobService,useClass:MockJobService}
。然后测试工作,但是,我想在subscribeEvent
函数上运行一个间谍,我需要useValue
版本才能工作。有什么问题吗?这取决于原始服务的实现,发布的代码无法解释为什么会出现错误
在这种情况下,useValue和useClass是可以互换的,但是new MockJobService()
应该放在每个之前的中,以便它们相等。使用新对象总是更好的
也可以使用useClass监视服务方法:
spyOn(MockJobService.prototype, 'subscribeEvent').and...
监视方法不会调用实际方法:
这就是为什么你会得到
无法读取未定义的属性“subscribe”
因为你没有返回可观察对象,而观察者没有任何订阅
将以下选项添加到spy,以便可以调用内部方法:
spyOn(component.mockJobService, 'subscribeEvent').and.callThrough()
spyOn(component.mockJobService, 'subscribeEvent').and.callFake(myFunction)
或者,定义要调用的假函数:
spyOn(component.mockJobService, 'subscribeEvent').and.callThrough()
spyOn(component.mockJobService, 'subscribeEvent').and.callFake(myFunction)