Question presented to candidate:
"ProfileComponent injects a UserService that calls HttpClient and an analytics method. How would you unit test the component without real HTTP or analytics, using spies? Show it in the runner the project uses, and say how the Jasmine version would differ."
What a strong answer should cover:
- Mocking works through dependency injection: replace the service token in
TestBed.configureTestingModule({ providers })withuseValue(a spy object) oruseClass(a fake class). - Vitest (the Angular 21+ CLI default):
vi.fn(),mockReturnValue(of(...)),vi.spyOn(service, 'method'),toHaveBeenCalledWith; Jest'sjest.fn()/jest.spyOn()have the same shape. - Jasmine:
jasmine.createSpyObj('UserService', ['getUser']),.and.returnValue(...),spyOn(obj, 'm').and.callThrough(). - Key difference:
vi.spyOncalls the real method unless you mock it; Jasmine'sspyOnstubs it unless you addand.callThrough(). - Return Observables from mocked methods (
of,throwError) so the component's subscribe logic is exercised, including the error path. - For HTTP specifically,
provideHttpClientTesting()+HttpTestingControllerfakes the backend instead of the service. - Component-level
providersare not replaced by TestBed providers; useTestBed.overrideComponent.
Clarifying questions expected:
- "Which runner: Vitest, Jest, or Karma with Jasmine?"
- "Is the service provided in root or in the component's own providers?"
Code / implementation expected: Yes β a component spec with a useValue spy mock, a spyOn on the real service, and an HttpTestingController variant.