Skip to the page

Testing Angular · Concept

Testing a component with TestBed

The 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

  1. What does fixture.detectChanges() do, and what is whenStable() for?
  2. How do you set a signal input in a test?
  3. How do you replace a real service with a fake?
  4. What are component harnesses?
  5. What do you avoid testing?
  6. 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 with fixture.componentRef.setInput('name', 'x'), find elements with fixture.nativeElement.querySelector(...), click, await fixture.whenStable(), check the text.
  • TestBed is zoneless by default (v21+): prefer await fixture.whenStable(); detectChanges() still works.
  • Fakes: useValue with vi.fn() (or Jasmine spies); provideHttpClientTesting() for HTTP; provideRouter([]) and RouterTestingHarness for routing.
  • Harnesses (CDK): TestbedHarnessEnvironment.loader(fixture) then loader.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 voice

Practise 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.

Start your free interview