14

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 }
    ]
});
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Salauddin Shaikh
  • 181
  • 1
  • 1
  • 5

3 Answers3

24

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

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
user2555964
  • 920
  • 7
  • 9
4

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 }
  ]
});
Fabio Picheli
  • 939
  • 11
  • 27
1

Did you try to add the APP_BASE_HREF as a provider?

{provide: APP_BASE_HREF, useValue : '/' }
Anouar
  • 42
  • 1
  • 13