You should use now RouterTestingHarness ( https://angular.dev/api/router/testing/RouterTestingHarness ) since Angular 15.2 as RouterTestingModule is deprecated ( https://angular.dev/api/router/testing/RouterTestingModule )
see the video made by Rainer Hahnekamp (12 minutes) : https://www.youtube.com/watch?v=DsOxW9TKroo ( from https://www.rainerhahnekamp.com/en/how-do-i-test-using-the-routertestingharness/ )
The production code (you need to test the ngOnInit() method) :
ngOnInit(): void {
if (this.router.url.endsWith('admin/user-list')) {
this.activeLinkIndex = 1;
} else if (this.router.url.endsWith('admin/group-list')) {
this.activeLinkIndex = 2;
}
}
The test code :
import { RouterTestingHarness } from '@angular/router/testing';
describe('MyComponent', () => {
...
const routes: Routes = [
{ path: 'admin/user-list', component: UserListComponent },
{ path: 'admin/group-list', component: GroupListComponent },
];
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [MyComponent, ... ],
providers: [provideRouter(routes)],
}).compileComponents();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
...
it('should set activeLinkIndex to 2 when targetted URL is admin/group-list', async () => {
await RouterTestingHarness.create('admin/group-list');
component.ngOnInit();
expect(component.activeLinkIndex).toBe(2);
});
...