I am trying to test my component with angular 2 final, but I get an error because the component uses the routerLink
directive. I get the following error:
Can't bind to 'routerLink' since it isn't a known property of 'a'.
This is the relevant code of the ListComponent
template
<a
*ngFor="let item of data.list"
class="box"
routerLink="/settings/{{collectionName}}/edit/{{item._id}}">
And here is my test.
import { TestBed } from '@angular/core/testing';
import { ListComponent } from './list.component';
import { defaultData, collectionName } from '../../config';
import { initialState } from '../../reducers/reducer';
const data = {
sort: initialState.sort,
list: [defaultData, defaultData],
};
describe(`${collectionName} ListComponent`, () => {
let fixture;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
ListComponent,
],
}).compileComponents(); // compile template and css;
fixture = TestBed.createComponent(ListComponent);
fixture.componentInstance.data = data;
fixture.detectChanges();
});
it('should render 2 items in list', () => {
const el = fixture.debugElement.nativeElement;
expect(el.querySelectorAll('.box').length).toBe(3);
});
});
I looked at several answers to similar questions but could not find a solution that worked for me.
To write a test case for
routerLink
. You can follow the below steps.Import
RouterTestingModule
andRouterLinkWithHref
.Import
RouterTestingModule
in your moduleIn test case find the directive
RouterLinkWithHref
tot test for the existence of the link.You need to configure all the routing. For testing, rather than using the
RouterModule
, you can use theRouterTestingModule
from@angular/router/testing
, where you can set up some mock routes. You will also need to import theCommonModule
from@angular/common
for your*ngFor
. Below is a complete passing testUPDATE
Another option, if you just want to test that the routes are rendered correctly, without trying to navigate...
You an just import the
RouterTestingModule
without configuring any routesthen just check that the link is rendered with the correct URL path, e.g.
If you are not testing router related stuff, you can configure the test to ignore unknown directives with 'NO_ERRORS_SCHEMA'