Mocking Services and Dependencies
Provide test doubles via DI.
Mocking Services and Dependencies is a free Angular Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, and your progress syncs across the web and the CoddyKit app. The Angular Academy course includes 4 lessons in total.
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'))); // erroruseClass 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.
Learn HTML with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 38
- Lessons
- 144
Frequently Asked Questions
Is the “Mocking Services and Dependencies” lesson free?
Yes — any 3 lessons of the Angular Academy learning path, including “Mocking Services and Dependencies”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Angular Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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
- TestBed and Component Fixtures
- Testing Inputs, Outputs, and DOM
- Mocking Services and Dependencies
- Testing Signals and Async Code