Javascript 角度单元测试:错误:无法匹配任何路由。URL段:';主页/顾问';

Javascript 角度单元测试:错误:无法匹配任何路由。URL段:';主页/顾问';,javascript,angular,typescript,jasmine,Javascript,Angular,Typescript,Jasmine,我在angular 4.0.0应用程序下进行单元测试,我的真实组件中的某些方法通过以下方式调用手动路由: method(){ .... this.navigateTo('/home/advisor'); .... } 使用navigateTo是一种自定义路由方法,调用此方法: public navigateTo(url: string) { this.oldUrl = this.router.url; this.router.navigate([url], { sk

我在angular 4.0.0应用程序下进行单元测试,我的真实组件中的某些方法通过以下方式调用手动路由:

method(){
....
    this.navigateTo('/home/advisor');
....
}
使用navigateTo是一种自定义路由方法,调用此方法:

  public navigateTo(url: string) {
    this.oldUrl = this.router.url;
    this.router.navigate([url], { skipLocationChange: true });
  }
我有这个路由文件:

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 { }
奇怪的是,即使我的应用程序也运行良好,但测试抛出了以下错误:

失败:未捕获(承诺中):错误:无法匹配任何路由。统一资源定位地址 段:“主/顾问”错误:无法匹配任何路由。URL段: “主页/顾问”

似乎我缺少一些配置


有什么想法吗?

以下是我的评论:

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

import { RouterTestingModule } from '@angular/router/testing';
然后,在你的试验台上

imports: [RouterTestingModule]
现在您应该能够对组件进行单元测试了

编辑

要监视你的路线,你必须做的是

spyOn(component.router, 'navigate').and.returnValue(true);
你期望它看起来像

expect(component.router.navigate).toHaveBeenCalledWith('/home/advisor');

您需要
RouterTestingModule。与routes
类似:

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

我遇到了同样的问题。接受答案的解决方案对我不起作用,因为我不小心将HttpClientModule而不是HttpClientTestingModule添加到我的规范文件中。为避免“无法匹配任何路由”问题,请确保在需要的任何位置添加RouterTestingModule和HttpClientTestingModule

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule,
            HttpClientTestingModule,
        ],
        declarations: [
            AppComponent
        ],
    }).compileComponents();
}));

在我的控制台中,我在运行我的单元测试用例时由于子例程而出现此错误。通过在我的单元测试用例中实现以下方法,我能够解决这个问题

class RouterStub {
        url = '';
        navigate(commands: any[], extras?: any) { }
      }

beforeEach(async(() => {
    TestBed.configureTestingModule({
                    providers:[{ provide: Router, useClass: RouterStub }]
}).compileComponents();
}));

您是否正确导入了提供应用程序路径的模块?是的,功能上,这很好,我没有注意到任何问题,只是单元测试失败,因为@Ante Jablan Adamović您需要在
测试床中导入模块,尝试记录您的
路由器
或在调试模式下添加断点,并检查是否有任何已注册的路由。Ante Jablan Adamović正在导入路由器测试模块,如您在测试中所见,您是否模拟了路由器模块?如果是这样,怎么做?@trichetriche我已经导入了RouterTestingModule,我认为有一些特定的方式来实现它:RouterTestingModule.withRoutes(Approvutes)例如,但问题仍然存在,即使添加了fasmou RouterTestingModule(我理解;))@AnteJablanAdamović:即使使用RouterTestingModuleWell也无法工作如果您导入了它,现在您必须监视您的方法调用!你不应该让组件通过一条路径到达另一个组件,你应该测试组件,而不是另一个!你知道如何为路由做间谍吗?@trichetriche:几乎不知道,如果有这样做的例子,那将是有用的。我在按照建议做间谍时遇到以下类型脚本错误:
类型为“true”的参数不能分配给类型为“Promise”的参数。
。但是,当我将spy改为simply
spyOn(component.router,'navigate')它可以工作。@dandy74有没有一种简单的方法可以避免创建
BlankComponent
?如果您的单元测试只涉及当前组件,并且这是测试场景中的最后一步,那么您可以简单地使用它本身而不造成任何伤害,或者使用redirectTo而不是component:
[{path:'yourpath',redirectTo:'}]