Unit testing is crucial for testing the functionality of a component in isolation, without delving into features that fall outside the scope of that component. For example, there's no need to test the dialog.open
method separately when it can be covered within the unit tests of NewCustomDialog
.
- To begin, create a Stub like the one below to serve as a placeholder for
NewCustomDialog
:
export class NewCustomDialogStub{
open(){ return null; }
close(){ return null; }
// and other dummy methods required by "OpenPopUpComponent"
}
- Inject this
stub
using useClass
in the providers
array as shown:
describe('OpenPopUpComponent', () => {
let component: OpenPopUpComponent;
let fixture: ComponentFixture<OpenPopUpComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
declarations: [OpenPopUpComponent],
providers: [
{ provide: NewCustomDialog, useClass: NewCustomDialogStub }
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(OpenPopUpComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be defined',()=>{
expect(component).toBeDefined();
})
it('should call the "open" method of dialog when calling openModel()',()=>{
spyOn(component.dialog,'open').and.callThrough();
component.openModel();
expect(component.dialog.open).toHaveBeenCalled();
})
})
This serves as a fundamental approach to testing. If you wish to learn more about writing tests, feel free to visit this series of informative articles. You can also refer to this specific article for further insights.