Mocking services helps you test components without using real data or making real requests. It makes tests faster and more reliable.
0
0
Mocking services in tests in Angular
Introduction
When you want to test a component that depends on a service without calling the real service.
When the real service makes HTTP requests and you want to avoid network calls during tests.
When you want to control the data returned by a service to test different scenarios.
When the real service is not ready but you want to start writing tests.
When you want to isolate your component tests from external dependencies.
Syntax
Angular
class MockService { methodName() { return expectedValue; } } TestBed.configureTestingModule({ providers: [ { provide: RealService, useClass: MockService } ] });
Use useClass to replace the real service with a mock class.
You can also use useValue to provide a simple object as a mock.
Examples
This mock service returns a fixed user object instead of calling the real service.
Angular
class MockUserService { getUser() { return { id: 1, name: 'Test User' }; } } TestBed.configureTestingModule({ providers: [ { provide: UserService, useClass: MockUserService } ] });
This example uses
useValue to provide a simple mock object with a method.Angular
const mockUserService = { getUser: () => ({ id: 2, name: 'Mock User' }) }; TestBed.configureTestingModule({ providers: [ { provide: UserService, useValue: mockUserService } ] });
Sample Program
This test replaces the real UserService with MockUserService. The component uses the mock to get user data. The test checks that the component shows the mocked user name.
Angular
import { TestBed } from '@angular/core/testing'; import { Component } from '@angular/core'; import { UserService } from './user.service'; class MockUserService { getUser() { return { id: 1, name: 'Mocked User' }; } } @Component({ selector: 'app-user', template: '<p>{{ userName }}</p>' }) class UserComponent { userName = ''; constructor(private userService: UserService) { const user = this.userService.getUser(); this.userName = user.name; } } describe('UserComponent with mocked service', () => { let component: UserComponent; beforeEach(() => { TestBed.configureTestingModule({ declarations: [UserComponent], providers: [ { provide: UserService, useClass: MockUserService } ] }); const fixture = TestBed.createComponent(UserComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should display mocked user name', () => { expect(component.userName).toBe('Mocked User'); }); });
OutputSuccess
Important Notes
Always mock only what you need to keep tests simple.
Use spies if you want to check if a service method was called.
Remember to configure the testing module before creating the component.
Summary
Mocking services lets you test components without real dependencies.
Use useClass or useValue to provide mocks in Angular tests.
Mocking makes tests faster, more reliable, and easier to control.