Back to course

Testing Routing Scenarios

The Complete Angular Developer: From Zero to Hero

76. Testing Routing Scenarios

Testing routing logic involves ensuring components can successfully navigate, retrieve route parameters, and that guards correctly block or allow access.

1. Setting up the Router Testing Module

To test components that interact with the router (e.g., injecting Router or ActivatedRoute), we use RouterTestingModule or provide mock versions of these services.

typescript import { RouterTestingModule } from '@angular/router/testing'; import { ActivatedRoute } from '@angular/router'; import { of } from 'rxjs';

// Mock the ActivatedRoute snapshot and paramMap Observable const mockActivatedRoute = { snapshot: { paramMap: convertToParamMap({ id: '101' }) }, paramMap: of(convertToParamMap({ id: '101' })) };

TestBed.configureTestingModule({ imports: [ // Use RouterTestingModule.withRoutes([]) for simple tests RouterTestingModule.withRoutes([ { path: 'home', component: HomeComponent } ]) ], providers: [ // Provide the mock ActivatedRoute to the component being tested { provide: ActivatedRoute, useValue: mockActivatedRoute } ] });

2. Testing Component Navigation

We inject and spy on the Router service to ensure router.navigate() is called correctly.

typescript it('should navigate to home on success', inject([Router], (router: Router) => { spyOn(router, 'navigate');

component.loginSuccessful(); // Component logic that calls router.navigate(['/home'])

expect(router.navigate).toHaveBeenCalledWith(['/home']); }));

3. Testing Route Guards

We test guards by instantiating the guard via injection and calling the canActivate method directly, providing mock route snapshots if necessary.

typescript describe('AuthGuard', () => { let guard: AuthGuard; let authService: AuthService;

beforeEach(() => { // Setup AuthService mock or spy // ... guard = TestBed.inject(AuthGuard); });

it('should return true if user is logged in', () => { spyOn(authService, 'isLoggedIn').and.returnValue(true); expect(guard.canActivate()).toBe(true); }); });