Skip to the page

Production and testing · mid

Testing components and services with TestBed

TestBed builds a component with real or fake dependencies. Tests must wait correctly, use fake timers, and test HTTP with the testing controller.

The notes

What you must know

  • TestBed.configureTestingModule({ imports: [MyComponent], providers: [{ provide: OrdersApi, useValue: fakeApi }] }), then TestBed.createComponent.
  • Set inputs with fixture.componentRef.setInput("name", "x"), not by writing to the instance, which skips the input mechanism.
  • After a change, run change detection (fixture.detectChanges() or wait for stable) before you assert the DOM.
  • A broken test may assert inside a setTimeout after the test has finished, so the assertion never counts.
  • HTTP service tests: provideHttpClient() and provideHttpClientTesting(); since v21 provideHttpClientTesting() alone is enough with no interceptors.
  • Use HttpTestingController: expectOne, flush a response, and verify() that nothing is left.
  • Tests that pass locally but fail in CI often wait with a real setTimeout. Use fake timers (vi.useFakeTimers(), advanceTimersByTime) or fakeAsync with tick when Zone.js is loaded.

The red pen

Common traps: mistake → fix

  • Mistake: A real setTimeout wait is fine in tests

    Fix: it is flaky on slow machines.

  • Mistake: Setting componentInstance.name is the same as setting an input

    Fix: it bypasses the input mechanism.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you test a component with an input?
  2. How do you test a service that calls an API?
  3. Why do tests pass locally and fail in CI?
  4. What is wrong with a test that asserts inside setTimeout?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview