← Back to Angular, page 3

angular-0043 · Hard senior

How do you test services that call HttpClient, functional guards, and routing behaviour in Angular?

Use provideHttpClient with provideHttpClientTesting and the HttpTestingController to assert requests and flush fake responses, and call verify() after each test. Test functional guards through the router with RouterTestingHarness, or call them inside TestBed.runInInjectionContext. Fake only what is slow or external.

Full answer

Testing with HTTP. Provide the real HttpClient together with a testing backend: provideHttpClient() and provideHttpClientTesting() (the old HttpClientTestingModule is legacy). In a test:

  1. Call the service method and subscribe.
  2. const req = http.expectOne('/api/courses') finds the pending request and fails if there is none or more than one.
  3. Assert on req.request.method, headers, params, or body.
  4. req.flush(data) answers it. req.flush('x', { status: 500, statusText: 'Server Error' }) simulates an error. req.error(new ProgressEvent('error')) simulates a network failure.
  5. In afterEach, http.verify() checks that no unexpected request is left over.

Because interceptors are part of provideHttpClient, you test them the same way: add withInterceptors([...]) and check the headers on the captured request.

Testing a functional guard. Two options. A unit test runs the function in an injection context: TestBed.runInInjectionContext(() => authGuard(route, state)). An integration test is more realistic. RouterTestingHarness.create() gives a harness, and await harness.navigateByUrl('/admin') performs a real navigation with the real guard. Then assert on router.url or the rendered component with harness.routeNativeElement. The integration style also catches wiring mistakes in the route config.

General principles for a senior answer:

  • Fake the boundary (HTTP, storage, time), not your own services.
  • Prefer the test pyramid: many small unit tests, fewer integration tests, and a few end-to-end tests with Playwright or Cypress.
  • Control time with fakeAsync and tick, or with the Jasmine clock, so tests are quick and not flaky.
  • Do not test the framework (that @if works). Test your decisions.
  • Run tests in CI, and keep them fast enough that people run them locally.
typescript
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Component, Injectable, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { CanActivateFn, Router, provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { Observable } from 'rxjs';

interface Course {
  id: number;
  title: string;
}

@Injectable({ providedIn: 'root' })
export class CourseApi {
  private readonly http = inject(HttpClient);

  list(): Observable<Course[]> {
    return this.http.get<Course[]>('/api/courses', { params: { page: 1 } });
  }
}

@Injectable({ providedIn: 'root' })
export class Session {
  isAdmin(): boolean {
    return false;
  }
}

export const adminGuard: CanActivateFn = () =>
  inject(Session).isAdmin() ? true : inject(Router).createUrlTree(['/login']);

@Component({ selector: 'app-page', template: `<p>page</p>` })
class PageComponent {}

describe('CourseApi', () => {
  let http: HttpTestingController;
  let api: CourseApi;

  beforeEach(() => {
    TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
    http = TestBed.inject(HttpTestingController);
    api = TestBed.inject(CourseApi);
  });

  afterEach(() => http.verify());

  it('requests page 1 and returns the courses', () => {
    let result: Course[] | undefined;
    api.list().subscribe((courses) => (result = courses));

    const req = http.expectOne((r) => r.url === '/api/courses');
    expect(req.request.method).toBe('GET');
    expect(req.request.params.get('page')).toBe('1');
    req.flush([{ id: 1, title: 'Angular' }]);

    expect(result).toEqual([{ id: 1, title: 'Angular' }]);
  });

  it('surfaces a server error to the caller', () => {
    let status = 0;
    api.list().subscribe({ error: (e) => (status = e.status) });

    http.expectOne((r) => r.url === '/api/courses').flush('boom', { status: 500, statusText: 'Server Error' });

    expect(status).toBe(500);
  });
});

describe('adminGuard', () => {
  it('redirects a visitor to /login', async () => {
    TestBed.configureTestingModule({
      providers: [
        provideRouter([
          { path: 'admin', component: PageComponent, canActivate: [adminGuard] },
          { path: 'login', component: PageComponent },
        ]),
        { provide: Session, useValue: { isAdmin: () => false } },
      ],
    });

    const harness = await RouterTestingHarness.create();
    await harness.navigateByUrl('/admin');

    expect(TestBed.inject(Router).url).toBe('/login');
  });
});

Angular 20.3 with Jasmine. Type-checked in strict mode and run with `ng test` (Karma, headless Chrome): all three specs pass.

Key points

  • `provideHttpClient()` plus `provideHttpClientTesting()` plus `HttpTestingController`; always call `verify()`.
  • `expectOne`, then assert on the request, then `flush` data or an error.
  • Test guards through `RouterTestingHarness` for realism, or `runInInjectionContext` for unit speed.
  • Fake boundaries and control time to avoid flaky tests.

Common mistakes

  • Forgetting `verify()`, so extra or missing requests go unnoticed.
  • Testing a guard only as a function and never checking that it is attached to the route.
  • Using real timers or real network calls in unit tests.

Follow-ups

  • How would you test an interceptor that retries on failure?
  • When would you pick an end-to-end test over a harness test?
  • How do you test a component that uses `@defer`?

Tips

  • Describe the testing layers you use and why. It shows engineering judgement.
  • Say you fake only boundaries. Over-mocking is a common weakness.
  • Mention `RouterTestingHarness` by name. It is the modern router test tool.

Evaluation rubric

  • Uses HttpTestingController correctly with verify.
  • Can test guards in unit and integration style.
  • Shows testing strategy awareness.