I need to mock a NgbModal to do some unit tests in angular, but I have no idea how to do this. This is my function:
openModal(deviceID: string, productID: string){
const modalRef = this.modalService.open(ProductModal)
modalRef.componentInstance.content = {
deviceId: deviceID,
productId: productID
}
modalRef.componentInstance.toEmit.subscribe(($e) => {
if ($e === true) this.reloadList();
});
}
What am I supposed to do?
compileComponents(); fixtureUnderTest = TestBed. createComponent(MyComponent); componentUnderTest = fixtureUnderTest. componentInstance; ngbModal = TestBed. get(NgbModal); }); it('should open modal', () => { spyOn(ngbModal, 'open').
A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.
Assuming your modalService
is NgbModal
, it seems the logic you want to test is inside the modal content (ProductModal
), not NgbModal
itself.
As you can see, after using .open()
your modalRef.componentInstance
will be an instance of ProductModal
; so you can test ProductModal
as any component with e.g. component fixtures and skipping the modalService
altogether:
(Again, assuming ProductModal
is a component with proper decorations.)
let component: ProductModal;
let fixture: ComponentFixture<ProductModal>;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ NgbModal, NgbActiveModal ],
declarations: [ ProductModal ]
});
fixture = TestBed.createComponent(ProductModal);
component = fixture.componentInstance;
fixture.detectChanges();
});
// now you have the component in `component`, so you can test
// component.content
// component.toEmit
// …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With