Angular:ngx 引导模式的单元测试用例覆盖率

时间:2021-01-21 16:19:38

标签: angular unit-testing jasmine code-coverage ngx-bootstrap

我有以下代码,我正在尝试为其编写单元测试用例:

    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();
         }
      });
    }

因此,当我单击登录按钮时,将调用 OnLogon 方法,该方法显示模态弹出窗口。另外,我已经订阅了模态组件的事件。

以下是我写的测试用例:

    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();
    })));

我创建了 BsModalService 存根,如下所示:

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

但是测试用例失败并出现错误“Expected spy processForgotDetails to have been called。”

有人可以帮助我做错的地方吗?我在 BsModalService 存根中使用事件的方式是否正确?

我正在尝试实现 onLogon() 方法的完整覆盖。

2 个答案:

答案 0 :(得分:0)

检查订阅调用中的测试是否有效

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'});
})));

答案 1 :(得分:0)

确保您已为 BsModalService 配置模块提供程序以返回模拟实现。

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