Angular 2 unit test : Cannot read property 'root' of undefined
21,111
Solution 1
The problem is that you're actually overriding the router to make your test, making it break the routerLink.
In other words: do not mock the Router
when using RouterTestingModule
. From your code, remove this line:
{ provide: Router, useClass: RouterStub }
You can see here a good explanation on how to unit test routes: Angular 2 Final Release Router Unit Test
Solution 2
I was facing the same error, the problem is: since you already have the declarations: [...TestComponent...]
it's not necessary add on providers
.
Your unit test file should be like this:
TestBed.configureTestingModule({
imports: [
MultilingualModule, CommonModule,
RouterTestingModule.withRoutes([
{
path: 'my-profile',
component: MockComponent
},
{
path: 'change-password',
component: MockComponent
},
])],
schemas: [ NO_ERRORS_SCHEMA ],
declarations: [TopNavigationBarComponent, TestComponent, MockComponent],
providers: [
{ provide: LoginService, useValue: MockLoginService }
]
});
Solution 3
Did you try to add the APP_BASE_HREF as a provider?
{provide: APP_BASE_HREF, useValue : '/' }
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
My template contain
<a [routerLink]="['/my-profile']" routerLinkActive="active"> <i class="icon-user"></i>{{ 'MY_PROFILE' | translate }} </a>
the error is because of
routerLink
androuterLinkActive
directives.Unit test file.
TestBed.configureTestingModule({ imports: [ MultilingualModule, CommonModule, RouterTestingModule.withRoutes([ { path: 'my-profile', component: MockComponent }, { path: 'change-password', component: MockComponent }, ]) ], schemas: [ NO_ERRORS_SCHEMA ], declarations: [TopNavigationBarComponent, TestComponent,MockComponent], providers: [ { provide: LoginService, useValue: MockLoginService }, { provide: Router, useClass: RouterStub } ] });