我正在尝试使用routerLink
和对(角度2)组件进行单元测试,routerLinkActive
但是所有测试用例均失败,并显示以下错误消息。(注意:我已经对路由器和其他相关的依赖项进行了存根。这是我用于相同的参考。)
无法读取未定义的属性“订阅”
我也注意到,当routerLink
和routerLinkActive
从我的模板被删除,所有测试用例将没有任何错误运行。
我认为该错误是由RouterTestingModule
或SharedModule
(包含用于显示和验证密码输入字段的组件)引起的。因此,我尝试删除或添加它们以查找实际上引起问题的原因。这是我观察到的。
Cannot read property 'subscribe' of undefined'
如果RouterTestingModule
或SharedModule
存在。RouterTestingModule
和时,我才不会收到与路由器相关的任何错误,SharedModules
但是中的元素SharedModules
不会加载到组件中,因此某些测试用例仍然会失败。TestBed配置:
TestBed.configureTestingModule({
imports: [CoreModule,SharedModule,RouterTestingModule],
declarations: [ MyComponent,RouterLinkStubDirective,RouterOutletStubComponent ],
providers: [
FormBuilder,
{ provide: Router, useClass: RouterStub },
{ provide: ActivatedRoute, userClass: ActivatedRouteStub}
],
schemas: [NO_ERRORS_SCHEMA]
})
.overrideComponent(MyComponent, {
set: {
providers: [
{provide: AuthModel, useClass: MockAuthModel}
],
}
})
.compileComponents();
}));
ActivatedRouterStub:
@Injectable()
export class ActivatedRouteStub {
// ActivatedRoute.params is Observable
private subject = new BehaviorSubject(this.testParams);
params = this.subject.asObservable();
// Test parameters
private _testParams: {};
get testParams() { return this._testParams; }
set testParams(params: {}) {
this._testParams = params;
this.subject.next(params);
}
// ActivatedRoute.snapshot.params
get snapshot() {
return { params: this.testParams };
}
}
我应该进行哪些更改以解决该问题?
我设法解决了这个问题。我将列出为解决该问题而进行的更改。
正如我在评论中提到的,routerLink
仅在真实路由器上有效。因此,我们需要包括RouterTestingModule (.withRoutes([{path: 'some/path',component: someComponent}])
如果您打算在测试时单击它,则包括在内)。
我们不需要单独提供路由器的依赖,如果我们已经添加RouterTestingModule
了。所以我删除了这两个Router
和ActivatedRoute
依赖,我提供的。现在,错误从Cannot read property 'subscribe' of undefined
变为Cannot read property 'outlets' of null
。
我发现当routerLink
指向空变量时会发生此错误。在我的情况下,由于隔离的测试环境favoriteUrl
,我分配给的属性称为routerLink
null。因此,我为函数中的属性手动分配了一个值,这beforeEach
至少可以解决我的问题。
感谢所有尝试提供帮助的人!:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句