Web Developer

Angular Unit Test: not use mock data in configureTestingModule because of @Component.providers: [Service]

Agnular unit test (standalone component), mock service in configureTestingmodule is set up, however, when running unit test, the mock service is not used, but using the real service instantiation, and one of the possible reasons is that the service is injected in the component level, like:

 

Codes:

@Component({

selector: ‘group-details’,

standalone: true,

imports: […],

providers: [GroupDetailsStore], <– DI service here

templateUrl: ‘./group-details.component.html’,

})

export class GroupDetailsComponent { … }

 

when you set up unit tests like:

 

Codes:


beforeEach(() => {
TestBed.configureTestingModule({
imports: [GroupDetailsComponent],
providers: [
{ provide: RedirectService, useValue: mockRedirectService }
// ❌ do not provide GroupDetailsStore here,
// it will be override by component.providers

]
});

 

the mock service will be override by real service instantiation, because providers: [GroupDetailsStore] in component level. So you have to override the service by providing like:

 

Codes:


TestBed.overrideComponent(GroupDetailsComponent, {
set: {
providers: [
{ provide: GroupDetailsStore, useValue: MockGroupDetailsStore }
]
}
});

 

full codes like:


beforeEach(() => {
TestBed.configureTestingModule({
imports: [GroupDetailsComponent],
providers: [ ]
}).overrideComponent(GroupDetailsComponent, {
set: {
providers: [
{ provide: GroupDetailsStore, useValue: MockGroupDetailsStore }
]
}
})
;

 

This will fix the issue.

Previous Article