Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 unit test : Cannot read property 'root' of undefined

My template contain

<a [routerLink]="['/my-profile']" routerLinkActive="active">
    <i class="icon-user"></i>{{ 'MY_PROFILE' | translate }}
</a>

the error is because of routerLink and routerLinkActive 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 }
    ]
});
like image 333
Salauddin Shaikh Avatar asked Nov 21 '16 12:11

Salauddin Shaikh


3 Answers

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

like image 99
user2555964 Avatar answered Nov 19 '22 20:11

user2555964


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 }
  ]
});
like image 4
Fabio Picheli Avatar answered Nov 19 '22 21:11

Fabio Picheli


Did you try to add the APP_BASE_HREF as a provider?

{provide: APP_BASE_HREF, useValue : '/' }
like image 1
Anouar Avatar answered Nov 19 '22 21:11

Anouar