简体   繁体   中英

Angular: Unit test case coverage for ngx bootstrap modal

I have the following code which I am trying to write unit test case for:

    onLogon(event: any, resetPassword = false): void {
      this.bsModalRef = this.modalService.show(
         LoginComponent,
         Object.assign(
            {},
            {
               animated: true,
               keyboard: false,
               backdrop: true,
               ignoreBackdropClick: true
            },
            { class: 'login-modal-popup' }
         )
      );

      this.bsModalRef.content.event.subscribe(data => {
         const type = data.type;
         this.bsModalRef.hide();
         if (type === 'register') {
            this.processRegister(false, true);
         } else if (type === 'forgot') {
            this.processForgotDetails();
         }
      });
    }

So, when I click the login button OnLogon method will be called which shows the modal popup. Also, I have subscribed to the events of the component of the modal.

Following is the test case that I wrote:

    it('should call processForgotDetails() method for the forgot event', async(inject([BsModalService], (modalService: BsModalService) => {
      spyOn(component, 'processForgotDetails');
      component.onLogon();
      component.bsModalRef.content.event.next({type: 'forgot'});
      fixture.detectChanges();
      expect(component.processForgotDetails).toHaveBeenCalled();
    })));

I created the BsModalService stub as below:

    const bsModalServiceStub = {
       show: jasmine.createSpy('show').and.callFake(function () {
          return {
             content: {
                event: new EventEmitter()
             }
          };
       }),
       hide: jasmine.createSpy('hide').and.callThrough(),
    };

But the test case failing with error "Expected spy processForgotDetails to have been called."

Can someone help where I am doing wrong? Is the way I used event in the BsModalService stub correct?

I am trying to achieve the complete coverage of the onLogon() method.

Check if testing inside the subscribe call will work

it('should call processForgotDetails() method for the forgot event', async(inject([BsModalService], (modalService: BsModalService) => {
  spyOn(component, 'processForgotDetails');
  component.onLogon();
  this.bsModalRef.content.event.subscribe(() => {
    expect(component.processForgotDetails).toHaveBeenCalled();
  });
  component.bsModalRef.content.event.next({type: 'forgot'});
})));

Make sure you have configured module provider for BsModalService to return mocked implementation.

TestBed.configureTestingModule({
    ...
    providers: [{ provide: BsModalService, useValue: bsModalServiceStub }]
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM