我为我正在测试的组件创建了一个测试(spec)文件.但是当我运行测试时,它给出了一个错误说法
Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
at ComponentUndertest.ngOnInit
Run Code Online (Sandbox Code Playgroud)
这是显而易见的,因为我已经在ngOnInit()方法中订阅了某些内容,但是我可以在测试期间忽略订阅吗?或者我可以在测试期间伪造订阅吗?我已经搜索了很多关于这个问题但是找不到与angular2测试有关的任何内容.提前致谢.
在测试具有共享服务的简单组件时,出现以下错误消息,我无法使其正常工作,我已经尝试了所有方法!
类型错误:无法读取未定义的属性“订阅”
lr.component.ts
export class LrComponent implements OnDestroy {
currentRouter: string;
private subscription: Subscription;
constructor(private lrService: LrService) {
this.subscription = this.lrService.lrNavigation$.subscribe(
(currentNav: string) => {
this.currentRouter = currentNav;
},
(error) => {
console.warn(error);
}
);
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
Run Code Online (Sandbox Code Playgroud)
lr.service.ts
@Injectable()
export class LrService {
// Observables for our components to subscribe to.
lrNavigation$: Observable<string>;
// Subjects to return data to subscribed components
private lrNavigationSubject = new Subject<string>();
constructor() {
this.lrNavigation$ = this.lrNavigationSubject.asObservable();
} …Run Code Online (Sandbox Code Playgroud)