I am trying to verify routing in the following very simple component:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'side-bar',
templateUrl: '
<div class="sidebar hidden-sm-down">
<div class="sidebar-block" >
<a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">Home</a>
</div>
<div class="sidebar-block">
<a routerLink="/edit" routerLinkActive="active">Edit</a>
</div>
</div>
',
styleUrls: ['./side-bar.component.scss']
})
export class SideBarComponent implements OnInit {
ngOnInit() { }
}
I currently have:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { RouterTestingModule } from '@angular/router/testing';
import { RouterLinkStubDirective } from '../../../testing/router-stubs';
import { SideBarComponent } from './side-bar.component';
describe('SideBarComponent', () => {
let component: SideBarComponent;
let fixture: ComponentFixture<SideBarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [SideBarComponent, RouterLinkStubDirective ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SideBarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('can be instantiated', () => {
expect(component).not.toBeNull();
});
it('can link to main pages', () => {
var linkElements = fixture.debugElement.queryAll(By.directive(RouterLinkStubDirective));
var links = linkElements.map(element => element.injector.get(RouterLinkStubDirective) as RouterLinkStubDirective);
expect(links.length).toBe(2, 'should have 3 links');
expect(links[0].linkParams).toBe('/', '1st link should go to Home');
expect(links[1].linkParams).toBe('/edit', '2nd link should go to Edit');
});
it('can show the active link', () => {
var activeLinks = fixture.debugElement.queryAll(By.css('.active')).map(element => element.injector.get(RouterLinkStubDirective) as RouterLinkStubDirective);
expect(activeLinks.length).toBe(0, 'should only have 1 active link');
expect(activeLinks[0].linkParams).toBe('/', 'active link should be for Home');
});
});
The first few tests work and follow the example set out in the official documentation on angular testing, with the only difference - I had to import the RouterTestingModule so that routerLinkActiveOptions did not cause an error.
The goal of the final test is to confirm that routerLinkActive is working as expected. I do not expect the current implementation to work, ideally I could set the current route and then check if the active link is set correctly, as in the previous test.
RouterTestingModule , , . - , .