我试图测试以下组件。
MyComponent -
export class MyComponent {
radioItems: any;
selectedItem: number = 0;
name: string;
constructor(private _reset: ForgotPwdService, private _router: Router) {
if (!_reset.storedMails || !_reset.fullName) {
_router.root.navigate(['ParentRoutePath']); // Using parent route, _router.parent.navigate() doesn't work for test either
return;
}
this.name = _reset.fullName;
this.radioItems = _reset.storedMails;
}
getValue(event) {
this.selectedItem = event;
}
onClick() {
this._reset.mail = this.radioItems[this.selectedItem].title;
this._router.navigate(['RoutePath']); //Using route
}
}
在测试中,在beforeEach()
方法中,我提供了以下路由组件 - provide(ROUTER_PRIMARY_COMPONENT, {useValue: ComponentWithChildRoute})
。
但是,当我尝试运行测试时,我在测试中遇到以下错误,尝试验证构造函数中的代码 - Component "ComponentWithChildRoute" has no route named "ParentRoutePath".
如果我尝试提供provide(ROUTER_PRIMARY_COMPONENT, {useValue: RootRouteComponent})
,我和#39;在运行Component "RootRouteComponent" has no route named "RoutePath".
方法的测试中出现onClick()
错误。
有办法解决吗?也许我可以在所需的测试中提供一个路由组件,而不是在beforeEach()中?
两项测试的代码 -
it('should redirect to login when storedMails or fullName are empty',
fakeAsync(inject([ForgotPwdService, Location, Router],
(forgot: ForgotPwdService, location: Location, route: Router) => {
forgot.storedMails = '';
let mail = new NameSent(forgot, route);
tick();
expect(location.path()).toContain('/login');
})
)
);
it('should direct to selected item when specified',
fakeAsync(inject([NameSent, Location], (name: NameSent, location: Location) => {
name.onClick();
tick();
expect(location.path()).toContain('/mail-sent');
}))
);
我设法通过以下方式重写这些测试来解决这个问题 -
it('should direct to selected item when specified',
fakeAsync(inject([NameSent, Router], (name: NameSent, router: Router) => {
spyOn(router, 'navigate');
name.onClick();
expect(router.navigate).toHaveBeenCalledWith(['MailSent']);
}))
);
但是,如果有可能以某种方式注入多个路径组件,我仍然感兴趣吗?