Testing Angular · Concept
Testing a component with TestBed
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
How do you unit test an Angular component? Walk me through TestBed and the fixture, and how you check that clicking a button changes what's on screen.
Then
Follow-ups the interviewer asks next
- What does fixture.detectChanges() do, and what is whenStable() for?
- How do you set a signal input in a test?
- How do you replace a real service with a fake?
- What are component harnesses?
- What do you avoid testing?
- Which test runner does a new Angular project use?
The answer
What a strong answer covers
TestBed.configureTestingModule({ imports: [MyComponent], providers: [{ provide: OrdersApi, useValue: fakeApi }] }),fixture = TestBed.createComponent(MyComponent), inputs withfixture.componentRef.setInput('name', 'x'), find elements withfixture.nativeElement.querySelector(...), click,await fixture.whenStable(), check the text.- TestBed is zoneless by default (v21+): prefer
await fixture.whenStable();detectChanges()still works. - Fakes:
useValuewithvi.fn()(or Jasmine spies);provideHttpClientTesting()for HTTP;provideRouter([])andRouterTestingHarnessfor routing. - Harnesses (CDK):
TestbedHarnessEnvironment.loader(fixture)thenloader.getHarness(MatButtonHarness.with({ text: 'Save' })); tests survive changes to library markup. - Test what the user sees, not private methods.
- Runner: Vitest with jsdom is the default for new projects since v21 (
@angular/build:unit-test); Karma is still supported.
The red pen
Common traps
Avoid:testing implementation details; assigning componentInstance.x = … for inputs (doesn't work for signal inputs); no assertion after the event.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.