Can't bind to 'routerLink' since it isn't a known property of 'a'. ("<header id="header">
Solution 1:
When you use the TestBed
you are configuring a module from scratch. In your current configuration, all you have is
TestBed.configureTestingModule({
declarations: [
AppComponent
],
});
So all that's included in the module for the test environment is the AppComponent
. Nothing from the AppModule
is included.
So you're getting the error because you are missing all the router directives that are included in the RouterModule
. You could import the RouterModule
, but for tests, you should instead use the RouterTestingModule
import { RouterTestingModule } from '@angular/core/testing'
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([])
],
declarations: [
AppComponent
],
});
You can add routes to the withRoutes
.
See Also:
- Angular 2 unit testing components with routerLink
Solution 2:
This is your app.component.spec.ts
You should also add routerModule there
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports:[RouterModule.forRoot([])] //add the router module here as well
});
TestBed.compileComponents();
});
When you're testing your AppComponent , like I said , you should give the test bed what ever you've given to your root @NgModule
, so :
beforeEach( () => {
TestBed.configureTestingModule( {
imports : [
BrowserModule,
FormsModule,
HttpModule,
RouterTestingModule.withRoutes( [
{ path : '', redirectTo : '/home', pathMatch : 'full' },
{ path : 'home', component : HomeComponent },
{ path : 'about', component : AboutComponent },
{ path : 'experiments', component : ExperimentsComponent },
{ path : '**', component : HomeComponent }
] )
],
declarations : [
AppComponent,
AboutComponent,
HomeComponent,
ExperimentsComponent,
ExperimentDetailComponent
],
schemas : [
CUSTOM_ELEMENTS_SCHEMA
],
providers : [
ExperimentsService,
StateService
]
} );
TestBed.compileComponents();
} );