0Pricing
Angular Academy · Lesson

Mocking Services and Dependencies

Provide test doubles via DI.

Mocking Services and Dependencies is a free Angular Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Mock Dependencies

A component test should isolate the component. If it injects an HttpClient-backed service, you do not want real network calls. Instead you provide a test double: a fake object that returns controlled data so tests are fast and deterministic.

Providing a Fake via useValue

The simplest double is a plain object supplied with useValue. Provide it under the same injection token the component asks for.

const fakeApi = { getUser: () => of({ name: 'Ada' }) };
TestBed.configureTestingModule({
  imports: [ProfileComponent],
  providers: [{ provide: UserApi, useValue: fakeApi }],
});

Jasmine Spies

jasmine.createSpyObj builds a fake with spy methods so you can both stub return values and assert calls.

const apiSpy = jasmine.createSpyObj<UserApi>('UserApi', ['getUser']);
apiSpy.getUser.and.returnValue(of({ name: 'Ada' }));
TestBed.configureTestingModule({
  providers: [{ provide: UserApi, useValue: apiSpy }],
});

Asserting the Service Was Called

After acting on the component, verify the spy received the expected arguments.

fixture.componentInstance.load(7);
fixture.detectChanges();
expect(apiSpy.getUser).toHaveBeenCalledWith(7);
expect(apiSpy.getUser).toHaveBeenCalledTimes(1);

Returning Observables from Mocks

Services often return Observables. Use RxJS of() for synchronous success and throwError() for failures, so you can test both branches.

import { of, throwError } from 'rxjs';

apiSpy.getUser.and.returnValue(of({ name: 'Ada' }));     // success
apiSpy.getUser.and.returnValue(throwError(() => new Error('boom'))); // error

useClass for Reusable Fakes

When a fake is reused across many specs, define a class and wire it with useClass.

class FakeUserApi {
  getUser() { return of({ name: 'Test' }); }
}
TestBed.configureTestingModule({
  providers: [{ provide: UserApi, useClass: FakeUserApi }],
});

Mocking HttpClient with HttpTestingController

To test services that call HTTP without faking the whole service, import provideHttpClientTesting() and flush requests via HttpTestingController.

import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';

TestBed.configureTestingModule({
  providers: [provideHttpClient(), provideHttpClientTesting()],
});

Flushing an HTTP Request

Expect a request, respond to it with fake data, then verify no unexpected calls remain.

const http = TestBed.inject(HttpTestingController);
service.load();
const req = http.expectOne('/api/users/7');
expect(req.request.method).toBe('GET');
req.flush({ name: 'Ada' });
http.verify();

Overriding a Provider per Spec

Sometimes one test needs a different fake. Use TestBed.overrideProvider() before createComponent.

TestBed.overrideProvider(UserApi, {
  useValue: { getUser: () => throwError(() => new Error('fail')) },
});
const fixture = TestBed.createComponent(ProfileComponent);

Mock Just Enough

A good double implements only the methods the component actually uses. Over-mocking couples your test to internals; under-mocking lets real side effects leak. Match the public contract the component depends on.

Spy on Real Service Methods

You can also keep a real service but spy on one method using spyOn(instance, 'method'), useful when most of the service is harmless but one call must be intercepted.

const svc = TestBed.inject(AnalyticsService);
spyOn(svc, 'track');
fixture.componentInstance.onClick();
expect(svc.track).toHaveBeenCalledWith('click');

Quick Check

How do you make a fake assert calls AND control return values?

Recap

You replaced real dependencies with doubles using useValue, useClass, and Jasmine spies; returned Observables with of/throwError; tested HTTP via HttpTestingController; and overrode providers per spec. Mock only the contract the component uses.

Frequently asked questions

Is the “Mocking Services and Dependencies” lesson free?

Yes — the full text of “Mocking Services and Dependencies” is free to read here on the web, and the Angular Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Angular Academy course, upgrade to CoddyKit PRO.

What will I learn in “Mocking Services and Dependencies”?

Provide test doubles via DI. You practise Angular Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Angular Academy?

No prior experience is required. Angular Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Mocking Services and Dependencies” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Angular Academy lesson?

Yes. Every Angular Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. TestBed and Component Fixtures
  2. Testing Inputs, Outputs, and DOM
  3. Mocking Services and Dependencies
  4. Testing Signals and Async Code
← Back to Angular Academy