我正在使用身份验证创建入门工具包模板以及使用 CRUD 的示例 ( https://github.com/fransyozef/basic-login-angular )
现在我是单元测试的新手,我试图至少让创建组件的测试运行起来。但我被困住了
TypeError: Cannot read property 'subscribe' of undefined
我认为错误来自
resolveRoute() {
this.route.params.subscribe(params => {
if (params['id']) {
this.id = +params['id'];
this.getItem();
} else {
this.handleItemNotFound();
}
});
}
有人可以帮我解决这个问题吗?
最佳答案
您应该模拟您的路由策略。正如我所看到的,您在 TestBed 导入
中使用了 routingModule
。假设您的自己的 routingModule
仅提供您自己的路由,并且无法模拟/监视其他路由。因此,我鼓励您首先调整 test.helper.ts
内的 Test helper paths
export const TestRoutingImports = [
HttpClientTestingModule,
RouterTestingModule, // <-- Use RouterTestingModule instead
];
The(RouterTestingModule) modules sets up the router to be used for testing. It provides spy implementations of Location, LocationStrategy, and NgModuleFactoryLoader.
RouterTestingModule 提供模拟,RouterModule 不提供。
您应该做的第二件事是从测试台中删除您的provide
。这里就没有必要了。我的意思是以下部分:
{
provide: ActivatedRoute, useValue: {
snapshot: { params: { id: 1 } }
}
},
删除它,因为这将覆盖组件提供者。在你的情况下,不需要。
希望能帮到你。
关于javascript - Angular 单元测试类型错误: Cannot read property 'subscribe' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53702866/