Advanced
Testing components & services
TestBed, component harnesses, HttpTestingController and marble tests.
Angular testing centres on TestBed, which builds a testing module and renders a component in a ComponentFixture. You interact via the DOM or component harnesses (stable, refactor-proof test APIs).
TestBed is a flight simulator: it recreates the cockpit (component + DI) on the ground so you can exercise every control safely without leaving the hangar.
Key concepts
1
Services that call HTTP are tested with HttpTestingController, which lets you assert requests and flush fake responses — no real network. RxJS timing is verified with marble tests using a TestScheduler.
`HttpTestingController`marble testsHttpTestingControllerTestScheduler
2
Prefer testing behaviour through the public API and DOM over implementation details; mock dependencies via DI overrides so tests stay fast and isolated.
behaviour through the public API and DOM
3
Pitfall: forgetting fixture.detectChanges() after state changes, so the DOM never updates in the test. Best practice: one behaviour per test, and use harnesses to avoid brittle CSS selectors. Interview angle: how to test an effect or a debounced search without real timers.
Pitfall:Best practice:Interview angle:fixture.detectChanges()
typescript
it('loads users', () => {
TestBed.configureTestingModule({ providers: [provideHttpClientTesting()] });
const svc = TestBed.inject(UserService);
const http = TestBed.inject(HttpTestingController);
let result: User[] = [];
svc.getUsers().subscribe(u => (result = u));
http.expectOne('/api/users').flush([{ id: 1, name: 'Ada' }]);
expect(result.length).toBe(1);
});