Daria Domagała
Daria Domagała

Reputation: 783

Mock NgbModal in Angular

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?

Upvotes: 9

Views: 9092

Answers (1)

Jari Keinänen
Jari Keinänen

Reputation: 1439

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

Upvotes: 1

Related Questions