角单元测试检查延迟加载模块的当前路径

时间:2019-02-27 09:42:01

标签: angular unit-testing routes karma-jasmine angular-routing

让我快速描述一下我的问题。我正在尝试测试检查当前路线网址的简单方法。此方法仅返回布尔值,该值在html组件的ngIf中使用。该组件的打字稿文件如下所示:

export class StudentComponent {

  constructor(private router: Router) { }

  routesAreNotUsed() {
    return this.router.url === '/student' ? true : false;
  }
}

问题是这是延迟加载模块中的组件。这是应用程序组件的路由和StudentModule组件的路由:

AppRoutingModule:

export const routes: Routes = [
  {path: '', pathMatch: 'full', redirectTo: 'welcome'},
  {path: 'welcome', component: WelcomeComponent},
  {path: 'about', component: ProjectInfoComponent},
  {path: 'student', loadChildren: './student/student.module#StudentModule', canLoad: [AuthGuard]},
  {path: '**', redirectTo: '404'},
  {path: '404', component: PageNotFoundComponent}
];

StudentRoutingModule:

export const routes: Routes = [
    {
        path: '', component: StudentComponent,
        children: [
            {
                path: 'info', component: UserComponent
            },
            {
                path: 'grades', component: GradesComponent
            },
            {
                path: 'grades/:id/grade', component: GradeComponent
            },
            {
                path: 'teachers', component: TeachersComponent,
            },
            {
                path: 'teachers/:id/info', component: UserComponent,
            },
            {
                path: 'messages', component: MessagesComponent,
                children: [
                    {
                        path: 'message/:messageType/:id', component: MessageComponent
                    }
                ]
            }
        ]
    }
]

当用户单击“登录”按钮时,将触发延迟加载的模块。如您所见,该模块上的默认组件是StudentComponent。如果路由被触发,则当前URL为'/ student'(来自AppRoutingModule),但实际上,如果它涉及StudentRoutingModule,则仅为''。 如何在StudentComponent中为这种简单的 routesAreNotUsed()方法编写单元测试?

我不能使用RouterTestingModule.withRoutes(routesOfStudentModule),因为没有'/ student'url。同样,RouterTestingModule.withRoutes(routesOfAppModule)

有人可以提供mi解决方案,还是仅提供单元测试和 configuration 规范文件的伪代码?任何建议都会有帮助,尤其是在配置,伪造路由等方面。  预先谢谢你。

0 个答案:

没有答案