Sub topic 16
Testing Routed Components
Unit tests that create a component directly with TestBed.createComponent skip the router entirely. Those tests cannot tell you whether a :id parameter reaches the component's input, whether a guard redirects to /login, or whether a resolver's data arrives before the view renders. RouterTestingHarness runs real navigations inside a test and hands you the component the router activated, so you can test routing behavior directly.
This chapter assumes you can write basic TestBed tests with describe, it, and expect, and that you know the route configuration, guards, and resolvers from earlier chapters. The examples avoid runner-specific APIs such as jasmine.createSpy, so they run unchanged under Jasmine/Karma or Vitest with globals enabled.
The working model
RouterTestingHarness is a small test utility from @angular/router/testing. When you create it, it builds a hidden root component that contains a single <router-outlet>, using whatever router configuration you provided to TestBed. Each call to harness.navigateByUrl() does three things:
- It calls the real
Router.navigateByUrl(). Guards, resolvers, redirects, and input binding all run. - It waits for the navigation to finish.
- It runs change detection and returns the activated component instance, or
nullif no component was activated.
The harness exposes these members:
| Member | Purpose |
|---|---|
| `RouterTestingHarness.create(url?)` | Creates the harness and optionally performs an initial navigation |
| `navigateByUrl(url)` | Navigates and resolves to the activated component or `null` |
| `navigateByUrl(url, Type)` | Same, but throws if the activated component is not of that type |
| `routeNativeElement` | The DOM element of the activated component |
| `routeDebugElement` | The `DebugElement` of the activated component |
| `fixture` | The underlying `ComponentFixture` of the hidden root |
| `detectChanges()` | Runs change detection on the fixture |
The harness replaces the older RouterTestingModule, which is deprecated. You configure routing in tests the same way you do in main.ts, with provideRouter.
Testing route parameters as inputs
The ProductDetailComponent from earlier chapters receives :id through withComponentInputBinding() and navigates home with a query parameter. A test can check both behaviors through real navigation. Use a small test-only route table instead of importing app.routes.ts. The full table pulls in lazy routes and unrelated components, which makes failures harder to read.
// product-detail.component.spec.ts
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Router, provideRouter, withComponentInputBinding } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { ProductDetailComponent } from './product-detail.component';
@Component({ standalone: true, template: 'home page' })
class HomeStubComponent {}
describe('ProductDetailComponent routing', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideRouter(
[
{ path: 'home', component: HomeStubComponent },
{ path: 'products/:id', component: ProductDetailComponent }
],
withComponentInputBinding()
)
]
});
});
it('binds :id to the id input and renders it', async () => {
const harness = await RouterTestingHarness.create();
const detail = await harness.navigateByUrl('/products/42', ProductDetailComponent);
expect(detail.id).toBe('42');
expect(harness.routeNativeElement?.textContent).toContain('Product 42');
});
it('navigates home with a from query parameter', async () => {
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/products/42', ProductDetailComponent);
const button = harness.routeNativeElement!.querySelector('button')!;
button.click();
await harness.fixture.whenStable();
const router = TestBed.inject(Router);
expect(router.url).toBe('/home?from=42');
expect(harness.routeNativeElement?.textContent).toContain('home page');
});
});Note a few details. Route parameters are always strings, so the assertion compares against '42', not 42. The typed overload navigateByUrl(url, ProductDetailComponent) gives you a typed instance and fails loudly if a redirect sent you somewhere else. After the click, the navigation runs asynchronously, so the test awaits whenStable() before reading router.url. That URL includes the serialized query string.
Testing a functional guard
You can test a guard at two levels. An integration test navigates through the guard and checks where the router ended up. A unit test calls the guard function directly. Both need an injection context, because the guard calls inject().
Integration: navigate through the guard
// auth.guard.spec.ts
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
ActivatedRouteSnapshot,
Router,
RouterStateSnapshot,
UrlTree,
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 DashboardStubComponent {}
@Component({ standalone: true, template: 'login' })
class LoginStubComponent {}
function setup(loggedIn: boolean): void {
TestBed.configureTestingModule({
providers: [
{ provide: AuthService, useValue: { isLoggedIn: () => loggedIn } },
provideRouter([
{ path: 'dashboard', component: DashboardStubComponent, canActivate: [authGuard] },
{ path: 'login', component: LoginStubComponent }
])
]
});
}
describe('authGuard', () => {
it('lets a signed-in user reach the dashboard', async () => {
setup(true);
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/dashboard', DashboardStubComponent);
expect(page).toBeInstanceOf(DashboardStubComponent);
expect(TestBed.inject(Router).url).toBe('/dashboard');
});
it('redirects an anonymous user 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('returns a UrlTree when called directly', () => {
setup(false);
const result = TestBed.runInInjectionContext(() =>
authGuard({} as ActivatedRouteSnapshot, {} as RouterStateSnapshot)
);
expect(result).toBeInstanceOf(UrlTree);
expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/login');
});
});The redirect test calls the untyped navigateByUrl('/dashboard') on purpose. With the typed overload, the harness would throw because the router activated LoginStubComponent, not the dashboard.
The direct-call test uses TestBed.runInInjectionContext, which gives the guard access to inject() and the providers you set up. Passing empty snapshots works here because authGuard ignores its arguments. If a guard reads route.paramMap or state.url, build the fields it needs.
Which level to choose
| Question you want answered | Use |
|---|---|
| Does the guard return the right value for each input? | Direct call in `runInInjectionContext` |
| Is the guard actually attached to the right route? | Harness navigation |
| Does the redirect land on a working page? | Harness navigation |
| Does a `CanMatchFn` make the router fall through to another route? | Harness navigation |
Direct calls are fast and precise. Only navigation tests catch configuration mistakes, such as putting the guard on the wrong path or listing it under canActivateChild by mistake.
Testing a resolver
The productResolver from the resolvers chapter fetches a product by :id. A navigation test proves that the data reaches the component before it renders. These examples assume Product has id and name fields.
// product.resolver.spec.ts
import { Component, Input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
ActivatedRouteSnapshot,
RouterStateSnapshot,
convertToParamMap,
provideRouter,
withComponentInputBinding
} from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { Observable, firstValueFrom, of } from 'rxjs';
import { productResolver } from './product.resolver';
import { Product, ProductService } from './product.service';
@Component({ standalone: true, template: '{{ product.name }}' })
class ProductViewStubComponent {
@Input() product!: Product;
}
describe('productResolver', () => {
const requestedIds: string[] = [];
const fakeService = {
getProduct: (id: string): Observable<Product> => {
requestedIds.push(id);
return of({ id, name: 'Desk lamp' } as Product);
}
};
beforeEach(() => {
requestedIds.length = 0;
TestBed.configureTestingModule({
providers: [
{ provide: ProductService, useValue: fakeService },
provideRouter(
[
{
path: 'products/:id',
component: ProductViewStubComponent,
resolve: { product: productResolver }
}
],
withComponentInputBinding()
)
]
});
});
it('delivers resolved data to the component input', async () => {
const harness = await RouterTestingHarness.create();
const view = await harness.navigateByUrl('/products/7', ProductViewStubComponent);
expect(requestedIds).toEqual(['7']);
expect(view.product.name).toBe('Desk lamp');
expect(harness.routeNativeElement?.textContent).toContain('Desk lamp');
});
it('requests the product named by the route', async () => {
const route = { paramMap: convertToParamMap({ id: '9' }) } as unknown as ActivatedRouteSnapshot;
const result = TestBed.runInInjectionContext(() =>
productResolver(route, {} as RouterStateSnapshot)
);
const product = await firstValueFrom(result as Observable<Product>);
expect(product.id).toBe('9');
});
});The fake service returns of(...), which emits synchronously, so the navigation completes without timers. If your real service uses HttpClient, you have two options. You can fake the service as shown, or you can provide provideHttpClient() and provideHttpClientTesting() and flush the request with HttpTestingController. In the second case the harness promise does not resolve until you flush, so start the navigation, flush, and then await it.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for ActivatedRoute` | The component injects router services but the test has no router | Add `provideRouter([...])` to the providers |
| Input is `undefined` in the test but works in the app | Test router lacks `withComponentInputBinding()` | Use the same router features as the app |
| Harness throws "Unexpected routed component" | Typed `navigateByUrl` was used but a guard or redirect activated a different component | Use the untyped overload and assert on `router.url` |
| `router.url` still shows the old URL | Assertion ran before a click-triggered navigation finished | `await harness.fixture.whenStable()` first |
| `inject() must be called from an injection context` | Guard or resolver called directly | Wrap the call in `TestBed.runInInjectionContext` |
| Test hangs | Resolver waits on an HTTP request that was never flushed | Fake the service, or flush with `HttpTestingController` |
| Unrelated errors from other features | Test imports the full `app.routes.ts` | Use a minimal route table with stub components |
Exercises
Exercise
A test calls await harness.navigateByUrl('/admin', AdminComponent), but the route has a guard that redirects anonymous users to /login, and the test provides an AuthService fake that reports the user as logged out. What happens, and how should the test be written to check the redirect?
Show answer
The harness throws because the activated component is the login component, not AdminComponent. To check the redirect, call the untyped await harness.navigateByUrl('/admin') and then assert expect(TestBed.inject(Router).url).toBe('/login'), optionally also checking harness.routeNativeElement for the login page content.
Exercise
Write a test that checks navigating to /products/abc renders "Product abc" in ProductDetailComponent. Which router feature must the test configure, and what value type should you expect for the id input?
Show answer
Configure provideRouter([{ path: 'products/:id', component: ProductDetailComponent }], withComponentInputBinding()). Then const c = await harness.navigateByUrl('/products/abc', ProductDetailComponent); expect(c.id).toBe('abc'); expect(harness.routeNativeElement?.textContent).toContain('Product abc');. Route parameters are always strings.
Exercise
You want to verify that a CanMatchFn on a reports route makes the router skip it and fall through to a wildcard NotFound route for users without the "reports" permission. Is a direct call in runInInjectionContext enough? Explain.
Show answer
No. A direct call only shows that the function returns false. The fall-through to the next matching route is router behavior, so you need a harness navigation to /reports with a fake permission service, followed by an assertion that the activated component is the NotFound component.