Sub topic 15
Testing guards and resolvers
This chapter assumes you can write functional guards and resolvers, and that you know TestBed, Jasmine or Jest style describe/it, and basic RxJS. Functional guards are plain functions that call inject(). You test them by running them in an injection context with fake dependencies.
Why functional guards are easy to test
A functional guard has three inputs: the route snapshot, the router state snapshot, and whatever inject() returns. The router supplies the first two when it navigates. In a test you supply them yourself.
The only hard part is inject(). It works only inside an injection context, so calling authGuard(...) directly in a test throws NG0203. TestBed.runInInjectionContext() gives you that context. Providers come from TestBed.configureTestingModule, so you replace real services with stubs.
The general recipe has four steps:
- Configure
TestBedwithprovideRouter([])and stubs for the services the guard uses. - Build minimal fake snapshots. Cast them, and fill in only the fields the guard reads.
- Call the guard inside
TestBed.runInInjectionContext(). - Assert on the return value.
Testing a guard that returns a UrlTree
A redirect guard returns a UrlTree object. Comparing UrlTree objects directly is awkward. Serialize them with Router.serializeUrl() and compare strings.
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree, provideRouter } from '@angular/router';
import { AuthService } from './auth.service';
import { authGuard } from './auth.guard';
describe('authGuard', () => {
function runGuard(loggedIn: boolean, url: string) {
TestBed.configureTestingModule({
providers: [
provideRouter([]),
{ provide: AuthService, useValue: { isLoggedIn: () => loggedIn } },
],
});
return TestBed.runInInjectionContext(() =>
authGuard({} as ActivatedRouteSnapshot, { url } as RouterStateSnapshot),
);
}
it('allows logged-in users', () => {
expect(runGuard(true, '/admin')).toBe(true);
});
it('redirects anonymous users to /login and keeps the URL', () => {
const result = runGuard(false, '/admin');
const router = TestBed.inject(Router);
expect(result instanceof UrlTree).toBeTrue();
expect(router.serializeUrl(result as UrlTree)).toBe('/login?returnUrl=%2Fadmin');
});
});Notes on this test:
- The helper
runGuardconfiguresTestBedonce per call.TestBedresets between tests automatically, so each test gets fresh providers. toBeTrue()is Jasmine. In Jest, usetoBe(true).- The
{} as ActivatedRouteSnapshotcast is acceptable when the guard ignoresroute. If the guard readsroute.dataorroute.paramMap, build those fields in the fake.
Testing guards that return Observables or Promises
A guard may return Observable<boolean | UrlTree> or Promise<...>. The return type is a union, so you must normalize it before asserting. A small helper handles all three shapes.
import { isObservable, firstValueFrom, Observable } from 'rxjs';
export async function unwrap<T>(value: T | Promise<T> | Observable<T>): Promise<T> {
return isObservable(value) ? firstValueFrom(value) : await value;
}Use it in an async test:
it('resolves the async guard result', async () => {
const result = await unwrap(runGuard(true, '/admin'));
expect(result).toBe(true);
});firstValueFrom rejects if the Observable completes without emitting. That is useful here: a guard that never emits would hang the router, and the test then fails instead of passing silently.
For stubs that return Observables, use of(true) for synchronous values. Use a Subject when you need to control timing, then call next() yourself.
Testing canDeactivate
A canDeactivate guard receives the component instance as its first argument. You do not need TestBed for the component, only a plain object that satisfies the interface. If the guard does not call inject(), it needs no injection context either.
The guard uses window.confirm. Stub it with a spy so the test does not open a dialog.
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { unsavedChangesGuard } from './unsaved-changes.guard';
describe('unsavedChangesGuard', () => {
const route = {} as ActivatedRouteSnapshot;
const state = {} as RouterStateSnapshot;
it('allows leaving when there are no unsaved changes', () => {
const component = { hasUnsavedChanges: () => false };
expect(unsavedChangesGuard(component, route, state, state)).toBe(true);
});
it('asks for confirmation when changes exist', () => {
const confirmSpy = spyOn(window, 'confirm').and.returnValue(false);
const component = { hasUnsavedChanges: () => true };
expect(unsavedChangesGuard(component, route, state, state)).toBe(false);
expect(confirmSpy).toHaveBeenCalledTimes(1);
});
});A CanDeactivateFn takes four arguments: the component, the current route, the current state, and the next state. Passing all four keeps the TypeScript compiler satisfied.
Testing a resolver
A resolver is a function from a route snapshot to data. The fake snapshot needs to provide only what the resolver reads, which is usually paramMap. Build one with convertToParamMap.
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, RouterStateSnapshot, convertToParamMap } from '@angular/router';
import { of } from 'rxjs';
import { ProductService } from './product.service';
import { productResolver } from './product.resolver';
describe('productResolver', () => {
it('loads the product for the id parameter', async () => {
const getById = jasmine.createSpy('getById').and.returnValue(of({ id: '7', name: 'Lamp' }));
TestBed.configureTestingModule({
providers: [{ provide: ProductService, useValue: { getById } }],
});
const route = { paramMap: convertToParamMap({ id: '7' }) } as ActivatedRouteSnapshot;
const result = TestBed.runInInjectionContext(() =>
productResolver(route, {} as RouterStateSnapshot),
);
expect(await unwrap(result)).toEqual({ id: '7', name: 'Lamp' });
expect(getById).toHaveBeenCalledWith('7');
});
});The spy assertion matters. It proves the resolver read the right parameter, not only that the service returned something.
Testing resolver failure paths
The safeProductResolver from the earlier chapter turns an error into a RedirectCommand. Test the failure path by making the stub throw with throwError.
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, RedirectCommand, Router, RouterStateSnapshot, convertToParamMap, provideRouter } from '@angular/router';
import { throwError } from 'rxjs';
import { ProductService } from './product.service';
import { safeProductResolver } from './safe-product.resolver';
describe('safeProductResolver', () => {
it('redirects to /not-found when the request fails', async () => {
TestBed.configureTestingModule({
providers: [
provideRouter([]),
{ provide: ProductService, useValue: { getById: () => throwError(() => new Error('404')) } },
],
});
const route = { paramMap: convertToParamMap({ id: '999' }) } as ActivatedRouteSnapshot;
const result = await unwrap(
TestBed.runInInjectionContext(() => safeProductResolver(route, {} as RouterStateSnapshot)),
);
expect(result instanceof RedirectCommand).toBeTrue();
const redirect = result as RedirectCommand;
expect(TestBed.inject(Router).serializeUrl(redirect.redirectTo)).toBe('/not-found');
});
});Without a test like this, a broken catchError can reach production unnoticed, because the happy path still passes.
Testing guards through the real router
Unit tests prove each function in isolation. They do not prove the guard is attached to the route, or that guards and resolvers run in the order you expect. For that, use RouterTestingHarness, which performs a real navigation in a test.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { AuthService } from './auth.service';
import { authGuard } from './auth.guard';
@Component({ standalone: true, template: 'secret' })
class SecretComponent {}
@Component({ standalone: true, template: 'login page' })
class LoginComponent {}
describe('routing with authGuard', () => {
it('lands on /login when anonymous', async () => {
TestBed.configureTestingModule({
providers: [
provideRouter([
{ path: 'secret', component: SecretComponent, canActivate: [authGuard] },
{ path: 'login', component: LoginComponent },
]),
{ provide: AuthService, useValue: { isLoggedIn: () => false } },
],
});
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/secret');
expect(TestBed.inject(Router).url).toBe('/login?returnUrl=%2Fsecret');
expect(harness.routeNativeElement?.textContent).toContain('login page');
});
});This test covers the wiring: route configuration, guard, redirect, and the final rendered component. Use a few of these for critical flows and many cheap unit tests for the branching logic.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `NG0203: inject() must be called from an injection context` | Guard or resolver called directly | Wrap the call in `TestBed.runInInjectionContext()` |
| `NullInjectorError: No provider for Router` | Guard injects `Router`, but no router is provided | Add `provideRouter([])` to the providers |
| Assertion on a `UrlTree` fails with a confusing object diff | Comparing object structure | Compare `router.serializeUrl(tree)` strings |
| Test passes but the Observable never emitted | Subscribing without awaiting | Use `firstValueFrom` in an `async` test |
| `TypeError: Cannot read properties of undefined (reading 'get')` | Fake snapshot lacks `paramMap` | Add `paramMap: convertToParamMap({...})` |
Exercise
A canActivate guard returns inject(AuthService).isAdmin(), and isAdmin() returns Observable<boolean>. Write the steps to test the case where the user is not an admin, and say which helper turns the result into a value you can assert on.
Show answer
Configure TestBed with a stub AuthService whose isAdmin returns of(false). Call the guard inside TestBed.runInInjectionContext() with fake snapshots, in an async test. The guard returns an Observable, so pass it to firstValueFrom (or the unwrap helper) to get the emitted value, then expect(value).toBe(false). Because the guard injects a service, calling it outside the injection context would throw NG0203.
Exercise
Your resolver test passes, yet in the running app the resolved data never reaches the component. Which kind of test would catch this, and why can the unit test not?
Show answer
A test that navigates through the real router, such as one using RouterTestingHarness. The unit test calls the resolver function directly, so it never checks that the route configuration has the resolve entry, that the key name matches the component input or route.data key, or that withComponentInputBinding() is enabled. A harness navigation exercises that wiring.