Angular20 min read
Testing HTTP Calls with HttpTestingController
Test API services without real network calls using HttpTestingController.
Avery Wilson
August 25, 2025
4.8k169
Testing HTTP services should not hit the real backend. Angular provides HttpTestingController to fake responses.
## Service
```ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export type Product = { id: number; title: string };
@Injectable({ providedIn: 'root' })
export class ProductsApi {
constructor(private http: HttpClient) {}
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>('/api/products');
}
}
```
## Test
```ts
import { TestBed } from '@angular/core/testing';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
import { provideHttpClient } from '@angular/common/http';
import { ProductsApi } from './products.api';
describe('ProductsApi', () => {
it('returns products from API', () => {
TestBed.configureTestingModule({
providers: [ProductsApi, provideHttpClient(), provideHttpClientTesting()],
});
const api = TestBed.inject(ProductsApi);
const httpMock = TestBed.inject(HttpTestingController);
api.getProducts().subscribe(data => {
expect(data.length).toBe(2);
expect(data[0].title).toBe('Laptop');
});
const req = httpMock.expectOne('/api/products');
expect(req.request.method).toBe('GET');
req.flush([
{ id: 1, title: 'Laptop' },
{ id: 2, title: 'Phone' },
]);
httpMock.verify();
});
});
```
## What this gives you
- fast tests
- no real backend dependency
- ability to test error handling too
> Next: SSR in Angular, what it is and the gotchas.
#Angular#Testing#HTTP#Advanced