Unit Test Cases For Home Widget Development¶
How to correctly setup Unit Test Cases¶
Use overrideComponent
to set providers at the component level (inside the component decorator’s providers
array). Without it, using configureTestingModule()
sets providers at the module level in spec files, but the original providers remain at the component level, potentially causing incorrect mocking behavior.
The correct Unit Test Cases file setup :¶
Component :
@Component({
selector: 'contacts',
templateUrl: '',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
ContactsService
]
})
export class ContactsComponent {
private readonly widgetFrameworkUtilsService = inject(WidgetFrameworkUtilsService);
}
Configuration :
TestBed.configureTestingModule({
declarations: [ContactsComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
providers: [
{
provide: WidgetFrameworkUtilsService,
useValue: mockWidgetFrameworkUtilsService
}
]
}).compileComponents();
TestBed.overrideComponent(
ContactsComponent,
{
set: {
providers: [
{
provide: ContactsService,
useValue: mockContactsService
}
]
}
}
)
Usage :
it('should call API with correct string', () => {
const contactsService = fixture.debugElement.injector.get(ContactsService);
});
Alternatively, this approach can be useful when using TestBed.inject()
and you want to avoid rewriting all the tests.
Configuration :
TestBed.configureTestingModule({
declarations: [ContactsComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
providers: [
{
provide: WidgetFrameworkUtilsService,
useValue: mockWidgetFrameworkUtilsService
}
]
}).compileComponents();
TestBed.overrideProvider(ContactsService, {useValue: contactsService});
Usage :
const contactsService = TestBed.inject(ContactsService);