All topics
Testingbeginner

TestBed Fundamentals

Explain what TestBed does and how it creates an isolated Angular testing module for each test.

TestBed is Angular's testing utility for configuring a small, isolated Angular module purely for test purposes, and understanding it is prerequisite to almost every other Angular testing topic, since nearly all component and service tests are built on top of it. Interviewers ask about it early in any testing discussion to confirm you understand what's actually happening when a test file calls TestBed.configureTestingModule({...}).

It's like building a small, disposable stage set specifically for rehearsing one scene of a play, rather than requiring the entire theater and full production crew to be assembled just to practice a single actor's lines.

Key Concepts

1
TestBed.configureTestingModule({ declarations, imports, providers }) (or, for standalone components, simply imports: [MyStandaloneComponent]) sets up a miniature Angular application context specifically for the test, mirroring the same dependency injection and component compilation machinery the real application uses, but scoped entirely to that one test file (and typically reset between individual tests via beforeEach).
TestBed.configureTestingModule({ declarations, imports, providers })imports: [MyStandaloneComponent]beforeEach
2
Once configured, TestBed.createComponent(MyComponent) compiles and instantiates the component, returning a ComponentFixture — a wrapper providing access to the component instance itself, its rendered DOM (fixture.nativeElement/fixture.debugElement), and crucially, fixture.detectChanges(), which must be called manually to trigger change detection in tests, since Angular's automatic, ongoing change detection loop doesn't run inside the synchronous test environment the way it does in a real running application.
TestBed.createComponent(MyComponent)ComponentFixturefixture.nativeElementfixture.debugElementfixture.detectChanges()
3
A subtlety worth mentioning in a deeper interview answer: TestBed.inject(SomeService) is the modern way to retrieve any provider (a service, or even the component's own injector-scoped dependencies) directly from the test module's injector, and it's frequently used both to grab the real service under test and to grab mock/spy replacements that were registered in providers specifically to override the real implementation for that test.
TestBed.inject(SomeService)providers