Sub topic 16
Testing Routed Components
This chapter assumes you know Angular's TestBed, can write Jasmine or Vitest specs, and have read the earlier chapters on input binding and functional guards. The examples test the ProductDetailComponent and authGuard from those chapters.
Why Test Through the Router
A unit test that creates a component directly with TestBed.createComponent skips the router. That test cannot tell you whether :id actually reaches the id input, or whether a guard redirects correctly. RouterTestingHarness fixes this. It is a test utility from @angular/router/testing that creates a root component containing a RouterOutlet, runs real navigations against the routes you provide, and gives you the component that gets activated.
Testing Parameter Binding
Register the routes with provideRouter inside TestBed, using the same features as production, then navigate:
import { TestBed } from '@angular/core/testing';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { ProductDetailComponent } from './product-detail.component';
describe('ProductDetailComponent routing', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideRouter(
[{ path: 'products/:id', component: ProductDetailComponent }],
withComponentInputBinding()
)
]
});
});
it('binds :id to the id input', async () => {
const harness = await RouterTestingHarness.create();
const component = await harness.navigateByUrl('/products/42', ProductDetailComponent);
expect(component.id).toBe('42');
expect(harness.routeNativeElement?.textContent).toContain('Product 42');
});
});When you pass a component type as the second argument, navigateByUrl checks that the activated component has that type and returns it with the correct type. The harness runs change detection after the navigation, so the template already shows the bound value.
Testing a Guard Redirect
To test a guard, give it stub dependencies and check where the navigation ends up:
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Router, provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { authGuard } from './auth.guard';
import { AuthService } from './auth.service';
@Component({ standalone: true, template: 'Dashboard' })
class DashboardStub {}
@Component({ standalone: true, template: 'Login' })
class LoginStub {}
describe('authGuard', () => {
function setup(loggedIn: boolean) {
TestBed.configureTestingModule({
providers: [
{ provide: AuthService, useValue: { isLoggedIn: () => loggedIn } },
provideRouter([
{ path: 'dashboard', component: DashboardStub, canActivate: [authGuard] },
{ path: 'login', component: LoginStub }
])
]
});
}
it('redirects anonymous users to /login', async () => {
setup(false);
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/dashboard');
expect(TestBed.inject(Router).url).toBe('/login');
expect(harness.routeNativeElement?.textContent).toContain('Login');
});
it('allows signed-in users through', async () => {
setup(true);
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/dashboard', DashboardStub);
expect(TestBed.inject(Router).url).toBe('/dashboard');
});
});Stub components keep the test focused on the guard, so the real dashboard's own dependencies don't need to be provided.
Harness Members You Will Use
| Member | Purpose |
|---|---|
| `RouterTestingHarness.create(url?)` | Creates the root fixture, with an optional first navigation |
| `navigateByUrl(url, type?)` | Navigates and returns the activated component |
| `routeNativeElement` | DOM element of the routed component |
| `routeDebugElement` | `DebugElement` for queries with `By.css` |
| `detectChanges()` | Runs change detection after you change state yourself |
| `fixture` | The underlying `ComponentFixture` |
Common Mistakes
- Leaving out
withComponentInputBinding()in the test. Then the input staysundefinedeven though production works. - Passing a component type to
navigateByUrlwhen a guard redirects. The type check fails because a different component was activated. - Forgetting
await. Navigation is asynchronous, so any assertion that runs before it finishes sees stale state.
Exercise
You test a route { path: 'admin', component: AdminComponent, canActivate: [authGuard] } by calling await harness.navigateByUrl('/admin', AdminComponent) while the stubbed isLoggedIn returns false. The test throws an error instead of failing an expectation. Why, and how should you rewrite it?
Show answer
The guard returns a UrlTree to /login, so the activated component is the login component, not AdminComponent, and the harness's type check throws. Call navigateByUrl('/admin') without the type argument, then assert that TestBed.inject(Router).url is '/login'.