javascript / intermediate
Snippet
Injecting Mock Service Subclasses within Component Test Beds
Angular unit tests can override real service dependencies by providing derived mock classes using the `useClass` provider recipe in `TestBed.configureTestingModule`.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { TestBed } from '@angular/core/testing';import { ProfileComponent } from './profile.component';import { UserDataService } from './user-data.service';class MockUserDataService extends UserDataService {override fetchUserPermissions(): string[] {return ['READ', 'WRITE'];}}describe('ProfileComponent DI Hierarchy', () => {beforeEach(async () => {await TestBed.configureTestingModule({imports: [ProfileComponent],providers: [{ provide: UserDataService, useClass: MockUserDataService }]}).compileComponents();});it('instantiates the component with overridden service behavior', () => {const fixture = TestBed.createComponent(ProfileComponent);expect(fixture.componentInstance).toBeTruthy();});});
angular
Breakdown
1
class MockUserDataService extends UserDataService {
Inherits from the base service class to create an isolated mock implementation with overridden methods.
2
providers: [{ provide: UserDataService, useClass: MockUserDataService }]
Registers the mock class token substitute inside the isolated test dependency injection container.
3
const fixture = TestBed.createComponent(ProfileComponent);
Creates an instance of the component under test bound to the mocked dependency tree.