Mock NgbModal in Angular

8.8k views Asked by At

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?

1

There are 1 answers

0
Jari Keinänen On

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
// …