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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
TestBed.configureTestingModule({ imports: [MyComponent], providers: [{ provide: OrdersApi, useValue: fakeApi }] }), thenTestBed.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
setTimeoutafter the test has finished, so the assertion never counts. - HTTP service tests:
provideHttpClient()andprovideHttpClientTesting(); since v21provideHttpClientTesting()alone is enough with no interceptors. - Use
HttpTestingController:expectOne, flush a response, andverify()that nothing is left. - Tests that pass locally but fail in CI often wait with a real
setTimeout. Use fake timers (vi.useFakeTimers(),advanceTimersByTime) orfakeAsyncwithtickwhen 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
- How do you test a component with an input?
- How do you test a service that calls an API?
- Why do tests pass locally and fail in CI?
- 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 voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.