Angular › Testing with Jasmine & Karma

How would you test an Angular service that makes HTTP requests, without making real network calls during the test?

Advanced

Answer

You use Angular's HttpClientTestingModule and the HttpTestingController, which let you intercept outgoing requests during a test, verify the exact request was made correctly, and manually provide a fake response, all without any real network activity happening.
TestBed.configureTestingModule({
  imports: [HttpClientTestingModule],
  providers: [UserService]
});

const httpMock = TestBed.inject(HttpTestingController);
const service = TestBed.inject(UserService);

service.getUsers().subscribe((users) => expect(users.length).toBe(1));

const req = httpMock.expectOne('/api/users');
req.flush([{ name: 'Alice' }]);
Real-world example A test for a UserService confirms it makes exactly one request to the correct API endpoint and correctly processes the response, using HttpTestingController to simulate the server's reply without any real network call.

Common follow-ups: What does the expectOne method actually verify, and what happens if no matching request was made?;Why is it important to call httpMock.verify() at the end of these tests?