角度单位测试:错误:无法匹配任何路线.网址细分:'主页/顾问'

fir*_*baa 8 javascript jasmine typescript angular

我正在使用我的角度4.0.0应用程序进行单元测试,我的实际组件中的一些方法是通过以下方式调用手动路由:

method(){
....
    this.navigateTo('/home/advisor');
....
}
Run Code Online (Sandbox Code Playgroud)

使用navigateTo是一个自定义路由方法,调用此方法:

  public navigateTo(url: string) {
    this.oldUrl = this.router.url;
    this.router.navigate([url], { skipLocationChange: true });
  }
Run Code Online (Sandbox Code Playgroud)

我有这个路由文件:

import ...     // Components and dependencies

const homeRoutes: Routes = [
  {
    path: 'home', component: HomeComponent,
    children: [
      {
        path: 'registration',
        component: RegistrationComponent,
        children: [
          {
            path: 'synthese',
            component: SyntheseComponent
          },
          {
            path: 'queue',
            component: QueueComponent,
            children: [
              {
                path: 'queue-modal',
                component: QueueModalComponent
              },
              {
                path: 'confirm',
                component: ConfirmComponent
              }
            ]
          }
        ]
      },
      {
        path: 'toolbox',
        component: ToolboxComponent
      },
      {
        path: 'appointment',
        component: AppointmentRegistrationComponent
      },
      {
        path: 'appointment-validation',
        component: AppointmentValidationComponent
      },
      {
        path: 'datepicker',
        component: DatePickerComponent
      },
      {
        path: 'validation/:defaultNumber',
        component: ValidationComponent,
        children: [
                   {
                     path: 'synthese',
                     component: SyntheseComponent
                   }
                   ]
      },
      {
        path: 'modalField',
        component: ModalFieldComponent
      },
      {
        path: 'search',
        component: SearchComponent
      },
      {
        path: 'advanced-search',
        component: AdvancedSearchComponent
      },
      {
        path: 'tools',
        component: ToolsComponent
      },
      {
        path: 'advisor',
        component: AdvisorComponent
      },
      {
        path: 'pilote',
        component: PilotComponent
      },
      {
          path: 'blank',
          component: BlankComponent
        },
      {
        path: 'view-360/:id',
        component: View360Component,
        children: [
          {
            path: 'client',
            component: ClientComponent
          },
          {
            path: 'tools',
            component: ToolsAdvisorComponent
          },
          {
            path: 'valid-close',
            component: ValidCloseComponent
          },
          {
            path: 'application',
            component: ApplicationView360Component
          }
        ],
        canActivate: [AuthGuardAdviser]
      },
      {
        path: 'view-360',
        component: View360Component,
        children: [
          {
            path: 'client',
            component: ClientComponent
          }
        ],
        canActivate: [AuthGuardAdviser]
      },
      {
        path: 'contract',
        component: ContractComponent
      },
      {
        path: 'queue-again',
        component: QueueAgainComponent
      },
      {
        path: 'stock',
        component: StockComponent,
        children: [
          {
            path: 'mobile',
            component: MobileComponent
          },
          {
            path: 'stock-level',
            component: StockLevelComponent
          }
        ]
      },
      {
        path: 'usefull-number',
        component: UsefullNumberComponent
      },
      {
        path: 'admin',
        loadChildren: 'app/home/admin/admin.module#AdminModule',
        //           component: AdminComponent,
        canActivate: [AuthGuardAdmin]
      },
      {
        path: 'rb',
        loadChildren: 'app/home/rb/rb.module#RbModule',
        //        component: RbComponent
        //        canActivate: [AuthGuardAdmin]
      },
      {
        path: 'tools-advisor',
        component: ToolsAdvisorComponent
      },
      {
        path: 'catalog/:haveClient',
        component: CatalogComponent
      },
      {
        path: 'application',
        component: ApplicationComponent
      },
    ]
  },

   ];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(homeRoutes)
  ],
  exports: [
    RouterModule
  ],
  declarations: []
})
export class HomeRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

奇怪的是,即使我的应用程序也能很好地完成,但是测试会抛出这个错误:

失败:未捕获(承诺):错误:无法匹配任何路由.URL段:'home/advisor'错误:无法匹配任何路由.网址细分:'主页/顾问'

好像我有一些缺少的配置.

有任何想法吗 ??

dan*_*y74 35

你需要RouterTestingModule.withRoutes这样:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [
      RouterTestingModule.withRoutes(
        [{path: 'yourpath', component: BlankComponent}]
      )
    ],
    declarations: [
      BlankComponent,
      YourComponentBeingTested
    ]
  })
  .compileComponents()
}))
Run Code Online (Sandbox Code Playgroud)

  • 假设您的单元测试仅涉及当前组件,并且这将是测试场景中的最后一步,那么您可以简单地使用它本身而不会造成任何损害,或者使用redirectTo代替组件:`[{path:'yourpath',redirectTo:''} ]`。 (5认同)

小智 13

根据我的评论:

当您想要对路由器进行单元测试时,您必须使用测试模块,而不是实际模块.

从...开始

import { RouterTestingModule } from '@angular/router/testing';
Run Code Online (Sandbox Code Playgroud)

然后,在你的Testbed中

imports: [RouterTestingModule]
Run Code Online (Sandbox Code Playgroud)

现在,您应该能够对组件进行单元测试

编辑

要对您的路由进行间谍,您需要做的是

spyOn(component.router, 'navigate').and.returnValue(true);
Run Code Online (Sandbox Code Playgroud)

你期望看起来像

expect(component.router.navigate).toHaveBeenCalledWith('/home/advisor');
Run Code Online (Sandbox Code Playgroud)

  • @AnteJablanAdamović:即使与RouterTestingModule一起使用也不起作用 (2认同)
  • 按照建议执行间谍操作时,我遇到以下打字稿错误:`类型为“true”的参数不可分配给类型为“Promise<boolean>”的参数。但是,当我将间谍更改为简单的“spyOn(component.router, 'navigate');”时,它就可以工作了。 (2认同)