Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 848
Daria Domagała Avatar asked Aug 30 '17 11:08

Daria Domagała


People also ask

How do you test for ngbModal?

compileComponents(); fixtureUnderTest = TestBed. createComponent(MyComponent); componentUnderTest = fixtureUnderTest. componentInstance; ngbModal = TestBed. get(NgbModal); }); it('should open modal', () => { spyOn(ngbModal, 'open').

What is mocks in angular?

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.


1 Answers

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
// …
like image 84
Jari Keinänen Avatar answered Sep 22 '22 11:09

Jari Keinänen