Testing Services and HTTP with HttpTestingController

Angular 13 min min read Updated: Nov 16, 2026 Intermediate
Testing Services and HTTP with HttpTestingController
Intermediate Topic 2 of 3

A Simple Service Test

typescript @Injectable({ providedIn: 'root' }) export class CartService { private _items = signal<CartItem[]>([]); items = this._items.asReadonly(); total = computed(() => this._items().reduce((s, i) => s + i.price * i.qty, 0)); add(item: CartItem) { this._items.update(list => [...list, item]); } clear() { this._items.set([]); } } describe('CartService', () => { let service: CartService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(CartService); }); it('calculates the total', () => { service.add({ id: 1, name: 'Pen', price: 2, qty: 3 }); service.add({ id: 2, name: 'Book', price: 10, qty: 1 }); expect(service.total()).toBe(16); }); it('clears items', () => { service.add({ id: 1, name: 'Pen', price: 2, qty: 1 }); service.clear(); expect(service.items()).toEqual([]); }); });

Testing HTTP Calls

HttpTestingController lets you catch requests and give fake answers.

typescript import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; describe('PostService', () => { let service: PostService; let http: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()], }); service = TestBed.inject(PostService); http = TestBed.inject(HttpTestingController); }); afterEach(() => http.verify()); // fail if there are unexpected requests it('gets posts', () => { const fake: Post[] = [{ id: 1, userId: 1, title: 'Hi', body: '...' }]; let result: Post[] | undefined; service.getAll().subscribe(r => (result = r)); const req = http.expectOne('https://jsonplaceholder.typicode.com/posts'); expect(req.request.method).toBe('GET'); req.flush(fake); // send fake response expect(result).toEqual(fake); }); it('creates a post with POST', () => { service.create({ userId: 1, title: 'New', body: 'Body' }).subscribe(); const req = http.expectOne(r => r.method === 'POST'); expect(req.request.body.title).toBe('New'); req.flush({ id: 101 }); }); it('handles a server error', () => { let message = ''; service.getUsers().subscribe({ error: e => (message = e.message) }); http.expectOne('/api/users').flush('Oops', { status: 500, statusText: 'Server Error' }); expect(message).toContain('Server error'); }); });

Test an Interceptor

typescript describe('authInterceptor', () => { let http: HttpClient; let ctrl: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ providers: [ provideHttpClient(withInterceptors([authInterceptor])), provideHttpClientTesting(), { provide: AuthService, useValue: { token: () => 'abc123', logout: vi.fn() } }, ], }); http = TestBed.inject(HttpClient); ctrl = TestBed.inject(HttpTestingController); }); it('adds the bearer token', () => { http.get('/api/me').subscribe(); const req = ctrl.expectOne('/api/me'); expect(req.request.headers.get('Authorization')).toBe('Bearer abc123'); req.flush({}); }); });

Test a Functional Guard

typescript it('redirects to login when logged out', () => { TestBed.configureTestingModule({ providers: [ provideRouter([]), { provide: AuthService, useValue: { isLoggedIn: () => false } }, ], }); const result = TestBed.runInInjectionContext(() => authGuard({} as any, { url: '/dashboard' } as any)); expect(result.toString()).toContain('/login'); // UrlTree });

Fake Timers (Debounce, Delays)

typescript it('waits for debounce', () => { vi.useFakeTimers(); const spy = vi.fn(); component.search('ang', spy); vi.advanceTimersByTime(300); expect(spy).toHaveBeenCalledOnce(); vi.useRealTimers(); });
Jasmine users: Replace vi.fn() with jasmine.createSpy(), vi.useFakeTimers() with jasmine.clock().install() and toHaveBeenCalledOnce with toHaveBeenCalledTimes(1).
Marble testing: For complex RxJS streams use TestScheduler from rxjs/testing to test time-based operators without waiting.

Conclusion

Test services by injecting them with TestBed. For APIs add provideHttpClientTesting, catch requests with expectOne, send fake data with flush and call verify after each test.

Quick Summary: provideHttpClientTesting + expectOne + flush + verify.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators