简体   繁体   English

Angular 单元测试:错误:无法匹配任何路由。 URL 段:'home/advisor'

[英]Angular Unit testing : Error: Cannot match any routes. URL Segment: 'home/advisor'

Am working on unit testing under my angular 4.0.0 app , some method in my real component is calling manual routing via :我正在我的 angular 4.0.0 应用程序下进行单元测试,我的真实组件中的某些方法正在通过以下方式调用手动路由:

method(){
....
    this.navigateTo('/home/advisor');
....
}

with navigateTo is a custom routing method calling this :使用navigateTo是一种自定义路由方法,调用此方法:

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

i have this routing file :我有这个路由文件:

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 { }

Strangely , even my application goes fonctionnally well ,but the test throws this error :奇怪的是,即使我的应用程序运行良好,但测试抛出此错误:

Failed: Uncaught (in promise): Error: Cannot match any routes.失败:未捕获(承诺):错误:无法匹配任何路由。 URL Segment: 'home/advisor' Error: Cannot match any routes. URL 段:'home/advisor' 错误:无法匹配任何路由。 URL Segment: 'home/advisor' URL 段:'home/advisor'

it seems like i have some missing configuration .好像我缺少一些配置。

Any ideas ??任何想法?

You need RouterTestingModule.withRoutes like so:你需要RouterTestingModule.withRoutes像这样:

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

Following my comment :按照我的评论:

When you want to unit test your router, you have to use the testing module, not the actual one.当你想对你的路由器进行单元测试时,你必须使用测试模块,而不是实际的模块。

Start with从...开始

import { RouterTestingModule } from '@angular/router/testing';

Then, in your Testbed然后,在您的测试台中

imports: [RouterTestingModule]

Now you should be able to unit test your component现在您应该能够对您的组件进行单元测试

EDIT编辑

To make a spy on your routing, what you have to do is要监视您的路由,您必须做的是

spyOn(component.router, 'navigate').and.returnValue(true);

And you expect will look like你期望看起来像

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

I run into same issue.我遇到了同样的问题。 The solution of accepted answer doesn't work for me, because I accidentally added the HttpClientModule instead of HttpClientTestingModule to my Spec files.接受答案的解决方案对我不起作用,因为我不小心将 HttpClientModule 而不是 HttpClientTestingModule 添加到我的规范文件中。 To avoid the "Can not match any routes" issue be sure you add RouterTestingModule and HttpClientTestingModule everywhere it is needed.为避免“无法匹配任何路由”问题,请确保在需要的任何地方添加 RouterTestingModule 和 HttpClientTestingModule。

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

In my console, I am getting this error while running my unit test case because of SubRoute .在我的控制台中,由于SubRoute ,我在运行单元测试用例时收到此错误。 I am able to fix this issue by implementing the following way in my unit test case.我可以通过在我的单元测试用例中实现以下方式来解决这个问题。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 测试:未捕获错误:未捕获(承诺中):错误:无法匹配任何路由。 URL 段:“家” - Angular Testing: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'home' 角单元测试:未捕获错误:未捕获(承诺中):错误:无法匹配任何路线。 网址段:“注销” - Angular Unit Test: Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout' 错误:无法匹配任何路由。 URL 段:'?' - Error: Cannot match any routes. URL Segment: '?' 错误:无法匹配任何路线。 网址段:“帐户” - Error: Cannot match any routes. URL Segment: 'account' Angular 如何解决错误:无法匹配任何路由。 URL 段:“目录/测试”? - Angular how do I resolve Error: Cannot match any routes. URL Segment: 'catalog/test'? 角度故事书错误:无法匹配任何路线。网址细分:'iframe.html' - Angular storybook Error: Cannot match any routes. URL Segment: 'iframe.html' 无法匹配任何路线。 角度误差? - Cannot match any routes. Error in angular? 无法匹配任何路线。 URL 段:'auth/login' - Cannot match any routes. URL Segment: 'auth/login' ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。 URL 段:'2017-18' - ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '2017-18' 错误错误:未捕获(承诺),无法匹配任何路由。 URL 段 - ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM