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

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


You need RouterTestingModule.withRoutes like so:

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. To avoid the "Can not match any routes" issue be sure you add RouterTestingModule and HttpClientTestingModule everywhere it is needed.

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