Compare mocking options for dependencies in TestBed.
Skip to solutionKEEP THE
mediumFrontend
How do you mock services in Angular unit tests using Jasmine/Jest spies?
798 views
01
Understand the problem
testingservices
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Inject mock implementations using providers in TestBed.configureTestingModule. Create spy objects using jasmine.createSpyObj('Service', ['method']) or Jest mocks, override providers with useValue: spy, and stub method return values to assert on component behavior.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Testing a component by mocking its HTTP service dependency
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { UserProfileComponent } from './user-profile.component';
import { DataService } from './data.service';
describe('UserProfileComponent', () => {
let fixture: ComponentFixture<UserProfileComponent>;
let component: UserProfileComponent;
let mockDataService: jasmine.SpyObj<DataService>;
beforeEach(async () => {
mockDataService = jasmine.createSpyObj('DataService', ['getUserProfile']);
await TestBed.configureTestingModule({
imports: [UserProfileComponent],
providers: [
{ provide: DataService, useValue: mockDataService }
]
}).compileComponents();
fixture = TestBed.createComponent(UserProfileComponent);
component = fixture.componentInstance;
});
it('should render user details from mock backend service', () => {
mockDataService.getUserProfile.and.returnValue(of({ id: 1, name: 'Spy User' }));
fixture.detectChanges();
const p = fixture.nativeElement.querySelector('p');
expect(p.textContent).toContain('Spy User');
});
});05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 33 of 121 decoded in the Angular track. One more won't hurt.