Angular 角度单元测试中的测试路径方法返回类型错误
我正在编写单元测试的Angular应用程序。我的组件中有一个方法 MyComponent:Angular 角度单元测试中的测试路径方法返回类型错误,angular,jasmine,karma-jasmine,angular8,Angular,Jasmine,Karma Jasmine,Angular8,我正在编写单元测试的Angular应用程序。我的组件中有一个方法 MyComponent: route(element) { this.myService.Name(element.Name); this.myService.Code(element.Code); this.router.navigate(["myPage"], { relativeTo: this.routes}); } 我的服务: Name(data) { th
route(element) {
this.myService.Name(element.Name);
this.myService.Code(element.Code);
this.router.navigate(["myPage"], { relativeTo: this.routes});
}
我的服务:
Name(data) {
this.name.next(data);
}
Code(data) {
this.code.next(data);
}
private code = new BehaviorSubject("");
getCode = this.code.asObservable();
private name= new BehaviorSubject("");
getName = this.name.asObservable();
我的单元测试如下:
it('route() function should be called', () => {
component.route(mockData[0]);
var spy = spyOn(component, "route").and.callThrough();
expect(spy).toBeDefined();
})
我在运行测试用例时遇到以下错误:
TypeError:this.myService.Name不是函数
如何解决此问题?您需要将测试模块配置到测试文件中的
测试床中,然后通过将服务类添加到providers数组中向其中提供服务
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [
{ provide: MyService, useValue: MyService }
]
});
您甚至可以通过将另一个类传递给useValue
proprity来伪造测试中的服务。仅在测试时模仿原始行为
有关更多信息,请阅读您必须模拟myService
。您是否有测试台。配置测试模块?