Testing services and HTTP

Intermediate · 13 min

Testing an injectable service in isolation, and HttpTestingController for asserting on and responding to HTTP calls without a real network.

Before thisServices as shared stateHttpClient fundamentals

Genka · 13 min

Testing services and HTTP

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by GenkaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A service with no template to render is simpler to test than a component — construct it through TestBed (or sometimes directly with `new`), call its methods, assert on the result.
  • HttpTestingController intercepts HTTP calls a test's code makes and lets the test control exactly what response comes back — no real network request ever happens.
  • `httpMock.verify()` at the end of a test confirms every expected request actually happened — an unmatched expected call fails the test just as loudly as an unexpected one would.

A service without a template is a simpler test, structurally

Everything about TestBed from the previous lesson still applies here, but a service strips away the entire rendering half of the problem. There’s no template, no ComponentFixture, no detectChanges() call needed — a service is tested by constructing it, calling its methods directly, and asserting on what it returns or what internal state it changed:

describe('CartService', () => {
  let service: CartService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(CartService);
  });

  it('adds an item', () => {
    service.addItem({ id: 1, name: 'Widget' });
    expect(service.itemCount()).toBe(1);
  });
});

TestBed.inject() (rather than createComponent) is the service equivalent — it constructs the service through the same real injector, resolving whatever dependencies that service itself needs along the way, without any rendering machinery involved at all.

The problem a service that calls HttpClient creates

A service like UserService, injecting HttpClient and making real requests, raises an obvious problem for a test: you don’t want a unit test actually hitting a network, let alone a real backend. You need something that intercepts those calls, lets the test assert they happened correctly, and supplies a controlled, fake response instead of a real one.

describe('UserService', () => {
  let service: UserService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [UserService, provideHttpClient(), provideHttpClientTesting()],
    });
    service = TestBed.inject(UserService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  it('fetches users', () => {
    service.getUsers().subscribe((users) => {
      expect(users.length).toBe(2);
    });

    const req = httpMock.expectOne('/api/users');
    expect(req.request.method).toBe('GET');
    req.flush([{ id: 1 }, { id: 2 }]); // the fake response

    httpMock.verify();
  });
});

provideHttpClientTesting() swaps in a testing-specific HttpClient backend that never actually sends anything over the network — every request it intercepts instead. httpMock.expectOne('/api/users') asserts that exactly one matching request happened, and req.flush(...) supplies the fake response data that request should resolve with, which is what lets the .subscribe() callback above actually run and get asserted on, synchronously, inside the test.

httpMock.verify(): catching requests you expected but forgot to assert

httpMock.verify(), typically called at the end of a test, confirms that every request the test expected actually happened — and, just as usefully, that no unexpected requests were made that the test never accounted for. This catches a specific, easy-to-miss bug: a service quietly making an extra, unintended request somewhere, which would otherwise pass silently since nothing was asserting against it directly.

Testing an error response, not just a success

A service’s error-handling logic (the catchError pattern from a few lessons back) needs its own test, separate from the happy path above — and HttpTestingController makes an error just as easy to simulate as a success:

it('handles a failed request', () => {
  service.getUsers().subscribe({
    error: (err) => expect(err.message).toContain('Failed to load users'),
  });

  const req = httpMock.expectOne('/api/users');
  req.flush('Server error', { status: 500, statusText: 'Internal Server Error' });
});

req.flush(..., { status, statusText }) simulates a failed HTTP response instead of a successful one, which is exactly what’s needed to verify a service’s catchError logic actually does what it claims — without this, that error-handling code path would never run in any test at all, success-only testing being a common, easy way to leave it entirely unverified.

This lesson’s video builds exactly this HttpClientTestingModule-based pattern with a real service, with timestamps covering service testing and HTTP testing specifically; the linked “deeper” video focuses on the API-mocking side alone if you want a second, more concentrated example of just that piece.

Check yourself

  1. 01Why is a plain, dependency-free service generally simpler to unit test than a component?

    A service has no template to render, so there's no fixture, no detectChanges call, no DOM to query — a test constructs the service (often with `new` directly, or via `TestBed.inject()` if it has its own injected dependencies), calls its methods, and asserts on what comes back or what state changed. The entire rendering half of component testing simply doesn't apply.

  2. 02In a test using HttpTestingController, what does `httpMock.expectOne('/api/users')` actually do, and what happens if the code under test never makes that request?

    It asserts that exactly one request matching that URL was made, and gives the test a handle to respond to it with `.flush(mockData)` — supplying a fake response with no real network call involved. If the code under test never actually makes that request, `expectOne` fails the test immediately, since the expectation wasn't met; this is what makes `HttpTestingController` useful for verifying a service makes the calls it's supposed to, not just for faking responses to calls it happens to make.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark