如何编写有关ngBootstrap模态关闭事件的单元测试?

时间:2019-09-24 18:21:27

标签: angular unit-testing ng-bootstrap ng-bootstrap-modal

我有打开模态以批准删除项目的代码:

  handleDeleteMarkingPeriod(deleteModel: DeleteModel) {
    this.openModalToAcceptDelete('Are you sure you want to delete this item?', deleteModel);
  }

  openModalToAcceptDelete(message = '', deleteModel: DeleteModel) {
    this.deleteModalReference = this.modalService.open(DeleteApprovalModalComponent, {backdrop: 'static'});
    this.deleteModalReference.componentInstance.message = message;

    this.deleteModalReference.result.then((result) => {

      if (result.approve) {
        this.deleteMarkingPeriod(deleteModel);
      }

    }, (reason) => {
      console.log(reason);
    });
  }

this.deleteModalReference.result.then被触发时,我正在检查响应,如果result.approvetrue,则我正在采取措施。

问题是:如何从值this.deleteModalReference.result.then的.spec文件{approve: true}许诺中触发,我的测试用例如下:


      it('it should open modal and accept delete', () => {
        component.schoolCalendars = schoolCalendars;
        spyOn(component, 'deleteMarkingPeriod');

        component.handleDeleteMarkingPeriod({
          calendarId: '7',
          markingPeriodId: '18'
        });

        expect(modalService.open).toHaveBeenCalled();
        expect(component.deleteMarkingPeriod).toHaveBeenCalled();
});

测试响应为:

FAILED TESTS:
  ManageCalendarTableComponent
    markingPeriodForm
      delete
        ✖ it should open modal and accept delete
              Chrome 77.0.3865 (Mac OS X 10.14.5)

        Expected spy deleteMarkingPeriod to have been called.

一切正常,我只是不知道如何在.then()内部运行代码,这是对服务本身的嘲笑:

    modalService = TestBed.get(NgbModal);
    modalRef = modalService.open(DeleteApprovalModalComponent);

    spyOn(modalService, 'open').and.returnValue(modalRef);

0 个答案:

没有答案