mediumFrontend

How do you mock services in Angular unit tests using Jasmine/Jest spies?

798 views
01

Understand the problem

Compare mocking options for dependencies in TestBed.

testingservices
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

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.