Sub topic 15
Testing guards and resolvers
This chapter assumes you know Angular's TestBed, the functional guard and resolver forms from earlier chapters, and basic Jasmine or Jest syntax. Functional guards and resolvers are plain functions. They call inject(), so you have to run them inside an injection context. TestBed.runInInjectionContext does that.
The testing approach
A guard or resolver test has four steps:
- Configure
TestBedwith stub versions of the services the function injects. - Call the function inside
TestBed.runInInjectionContext. - Pass minimal fake
ActivatedRouteSnapshotandRouterStateSnapshotobjects, cast to the right types. - Assert on the return value. If it is an Observable or Promise, resolve it first.
Testing a guard that redirects
The guard returns a UrlTree when the user is anonymous. A UrlTree is an object, so compare its serialized string instead of the object.
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, provideRouter } from '@angular/router';
import { AuthService } from './auth.service';
import { authGuard } from './auth.guard';
describe('authGuard', () => {
function run(loggedIn: boolean) {
TestBed.configureTestingModule({
providers: [
provideRouter([]),
{ provide: AuthService, useValue: { isLoggedIn: () => loggedIn } },
],
});
return TestBed.runInInjectionContext(() =>
authGuard({} as ActivatedRouteSnapshot, { url: '/admin' } as RouterStateSnapshot),
);
}
it('allows logged-in users', () => {
expect(run(true)).toBe(true);
});
it('redirects anonymous users to /login', () => {
const result = run(false);
const router = TestBed.inject(Router);
expect(router.serializeUrl(result as any)).toBe('/login?returnUrl=%2Fadmin');
});
});Each test calls run once, so configureTestingModule is called once per test. Calling it twice in one test throws an error.
Testing an async resolver
A resolver often returns an Observable. Convert it to a Promise with firstValueFrom and await the result. The resolver return type is a union, so cast it to Observable first.
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot, RouterStateSnapshot, convertToParamMap } from '@angular/router';
import { Observable, firstValueFrom, of } from 'rxjs';
import { ProductService } from './product.service';
import { productResolver } from './product.resolver';
describe('productResolver', () => {
it('loads the product named by 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),
) as Observable<unknown>;
expect(await firstValueFrom(result$)).toEqual({ id: '7', name: 'Lamp' });
expect(getById).toHaveBeenCalledWith('7');
});
});If you use Jest, replace jasmine.createSpy(...).and.returnValue(...) with jest.fn().mockReturnValue(...).
Common errors
inject() must be called from an injection context: you called the function directly. Wrap it inrunInInjectionContext.NullInjectorErrorforRouter: the guard injectsRouterbut the test did not addprovideRouter([]).- Comparing
UrlTreeobjects withtoEqual: this is fragile. Userouter.serializeUrl. - Test passes without checking anything: an unresolved Observable never runs your assertions. Always
awaitit. - Unused snapshot fields: only fake the fields your function reads. A missing field the function does read gives
undefinedand a confusing failure.
Exercise
A canDeactivate guard calls window.confirm. How do you test the branch where the user declines, without opening a real dialog?
Show answer
Replace window.confirm with a stub that returns false (for example spyOn(window, 'confirm').and.returnValue(false) in Jasmine). Pass a fake component whose hasUnsavedChanges() returns true, call the guard directly, and expect the result to be false. A canDeactivate guard that does not call inject() needs no injection context.